Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enabling JSON Schema and Custom Parsing #61

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
152 changes: 152 additions & 0 deletions jsonSchema.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>XML to JSON Parsing with Schema</title>
<meta name="author" content="Dileep Miriyala(దిలీపు మిరియాల)" />
<style>
body {
font-family: 'Miriam Fixed';
}

table {
width: 100%;
border-collapse: collapse;
border: 0px solid black;
}

textarea {
width: 100%;
height: 160px;
font-size: 12px;
color: blue;
}

.label {
font-weight: bold;
color: red;
font-size: 16px;
}

.right {
text-align: right;
width: 100%;
}
</style>
</head>
<body>
<div>
<table cellpadding="2" cellspacing="2">
<tr>
<td style="text-align:right;">
<input type="button" id="btnClear" value="Clear" />
</td>
</tr>

<tr>
<td class="label">Xml:</td>
</tr>
<tr>
<td>
<textarea id="txtXML"></textarea>
</td>
</tr>
<tr>
<td class="label">JSON Schema:</td>
</tr>
<tr>
<td>
<textarea id="txtSchema"></textarea>
</td>
</tr>
<tr>
<td>&nbsp;</td>
</tr>

<tr>
<td>
<input type="button" id="btnGo" value="GO" />
</tr>
<tr>
<td>&nbsp;</td>
</tr>
<tr>
<td class="label">Xml Converted to JSON (using XML2JSON) :</td>
</tr>
<tr>
<td>
<textarea id="txtJSON"></textarea>
</td>
</tr>
<tr>
<td class="label">JSON honoring JSON Schema:(Along with Custom Parsing)</td>
</tr>
<tr>
<td>
<textarea id="txtJSONWithSchema"></textarea>
</td>
</tr>

</table>
</div>
<script type="text/javascript" src="xml2json.js"></script>
<script type="text/javascript">
function registerEvent(E, eventName, elementEventListener) {
if (E == null) {
return;
}
if (E.addEventListener != null) {
E.addEventListener(eventName, elementEventListener, false);
}
else if (E.attachEvent != null) {
E.attachEvent('on' + eventName, elementEventListener);
}
else {
E['on' + eventName] = elementEventListener;
}
}
function custom(x) {
return x + "___________________";
}
function init() {

var _xml_ = '<root><childs1><child id="p" /></childs1><childs2 pid="1" my="test"><child id="1" bool="true" /><child id="1.36" /><child /><child h="p" /></childs2></root>';
var _json_ = '{"root":{"childs1":{"child":[{"_id":0}]},"childs2":{"child":[{"_id":0,"_bool":true}],"_pid":0,"_my":"custom:custom"}}}';

document.getElementById("txtXML").value = _xml_;
document.getElementById("txtSchema").value = _json_;

registerEvent(document.getElementById("btnGo"), 'click', go);
registerEvent(document.getElementById("btnClear"), 'click', clear);
go();
}

function clear() {
document.getElementById("txtXML").value = "";
document.getElementById("txtSchema").value = "";
document.getElementById("txtJSON").value = "";
document.getElementById("txtJSONWithSchema").value = "";
}

function go() {
var _xml = document.getElementById("txtXML").value.toString();
var _schema = document.getElementById("txtSchema").value.toString();

try {
_schema = JSON.parse(_schema);
} catch (e) {
_schema = null;
}

var _json = new X2JS().xml_str2json(_xml);
var _json2 = (_schema == null) ? null : new X2JS({ jsonSchema: _schema }).xml_str2json(_xml);

document.getElementById("txtSchema").value = _schema == null ? "" : JSON.stringify(_schema, null, '\t')
document.getElementById("txtJSON").value = _json == null ? "" : JSON.stringify(_json, null, '\t');
document.getElementById("txtJSONWithSchema").value = _json2 == null ? "" : JSON.stringify(_json2, null, '\t');

}
init();
</script>
<div class="right"><span class="content">~ Dileep Miriyala(దిలీపు మిరియాల)</span></div>
</body>
</html>
22 changes: 22 additions & 0 deletions xml2json.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/*
Author: Dileep Miriyala
Last updated on : 05-Sep-2017 20:30:00EST
*/
declare type X2JSConfig = {
attributePrefix?: string;
emptyNodeForm?: string;
enableToStringFunc?: boolean;
arrayAccessFormPaths?: string[];
skipEmptyTextNodesForObj?: boolean;
stripWhitespaces?: boolean;
datetimeAccessFormPaths?: string[];
useDoubleQuotes?: boolean;
xmlElementsFilter?: string[];
keepCData?: boolean;
}
declare class X2JS {
constructor();
constructor(config: X2JSConfig);
xml_str2json(xmlText: string): Object;
json2xml_str(json: Object): string;
}
134 changes: 133 additions & 1 deletion xml2json.js
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@
};

function initRequiredPolyfills() {
setAcessFormPaths(config.jsonSchema, "");
}

function getNodeLocalName( node ) {
Expand Down Expand Up @@ -173,6 +174,133 @@
return d;
}

function setAcessFormPaths(jsonSchema, path) {
if (jsonSchema == null) {
return;
}
for (var prop in jsonSchema) {

var currSchema = jsonSchema[prop];
var srcType = typeof jsonSchema[prop];
var propPath = (path == "" ? "" : (path + "."));
var newPath = propPath + prop;

switch (srcType) {
case "object":
if (prop == "0") {
for (var index = 0; index < jsonSchema.length; index++) {
setAcessFormPaths(jsonSchema[index], path);
}
}
else {
if (Array.isArray(currSchema)) {
console.log(newPath + "[]");
config.arrayAccessFormPaths.push(newPath);
}
setAcessFormPaths(currSchema, newPath);
}
break;
default:
break;
}
}
};

function fixJSONTypes(src, target) {

if (src == null) {
return;
}

for (var prop in target) {

var srcType = typeof src[prop];
var targetType = typeof target[prop];

if (srcType == targetType) {
var currSchema = target[prop];
switch (srcType) {
case "object":
if (prop == "0") {
for (var index = 0; index < src.length; index++) {
fixJSONTypes(src[index], currSchema)
}
}
else {
fixJSONTypes(src[prop], currSchema)
}
break;
case "string":
var arr = currSchema.split(':')
if (arr.length < 2) {
break;
}
switch (arr[0]) //Target Format
{
case "date":
//Date Format being expected hence parse this value as date format
//TODO...
break;
case "custom":
var func = window[arr[1]];
if (func != null) {
src[prop] = func(src[prop]);
}
break;
}
break;
default:
break;
}
}
else {
if (src[prop] == null) {
return;
}

try {
switch (targetType) {
case "number":
switch (srcType) {
case "string":
var n = parseFloat(src[prop]);
if (!isNaN(n)) {
src[prop] = n;
}
break;
}
break;

case "boolean":
switch (srcType) {
case "string":
src[prop] = JSON.parse(src[prop]);
break;
}
break;

case "object":
switch (srcType) {
case "string":
if (src[prop] == "") {
src[prop] = {};
};
break;
}
break;
case "string":
//Some Custom String Formats may be defined.
default:
//Don't know how to handle
break;
}
} catch (e) {
//Ignore the if the parsing failed...
}
}
}
};

function checkFromXmlDateTimePaths(value, childName, fullPath) {
if(config.datetimeAccessFormPaths.length > 0) {
var path = fullPath.split("\.#")[0];
Expand Down Expand Up @@ -558,7 +686,11 @@
};

this.xml2json = function (xmlDoc) {
return parseDOMChildren ( xmlDoc );
var retVal = parseDOMChildren(xmlDoc);
if (config.jsonSchema != null) {
fixJSONTypes(retVal, config.jsonSchema);
}
return retVal;
};

this.xml_str2json = function (xmlDocStr) {
Expand Down