-
-
Save rezarahimi/4433104 to your computer and use it in GitHub Desktop.
Fixing problem in converting Axis WS results to JSON
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// One way converter from E4X XML to JSON | |
// 1) turns <body><item>1</item><item>2</item></body> into | |
// body: {item: ["1", "2"]} so that lists are easier to work with | |
// 2) turns things like: <body a="a">whatever</body> into | |
// body: {_a: "a", _: "whatever"} | |
// however <body>whatever</body> becomes simply body: "whatever | |
// - attributes specified by ignored are ignored | |
function E4XtoJSON(xml, ignored) { | |
var r, children = xml.*, attributes = xml.@*, length = children.length(); | |
if(length == 0) { | |
r = xml.toString(); | |
} else if(length == 1) { | |
var text = xml.text().toString(); | |
if(text) { | |
r = text; | |
} | |
} | |
if(r == undefined) { | |
r = {}; | |
for each (var child in children) { | |
var name = child.localName(); | |
var json = E4XtoJSON(child, ignored); | |
var value = r[name]; | |
if(value) { | |
if(value instanceof Array) { | |
value.push(json); | |
} else { | |
r[name] = [value, json] | |
} | |
} else { | |
r[name] = json; | |
} | |
} | |
} | |
if(attributes.length()) { | |
var a = {}, c = 0; | |
for each (var attribute in attributes) { | |
var name = attribute.localName(); | |
if(ignored && ignored.indexOf(name) == -1) { | |
a["_" + name] = attribute.toString(); | |
c ++; | |
} | |
} | |
if(c) { | |
if(r) a._ = r; | |
return a; | |
} | |
} | |
return r; | |
} | |
// test, requires ringo/ringojs and chl/wraps-tagsoup | |
var tagsoup = require("wraps/tagsoup"); | |
var data = tagsoup.parse("http://groups.google.com/group/ringojs/feed/atom_v1_0_msgs.xml"); | |
print(JSON.stringify(E4XtoJSON(data, ["type", "space", "xmlns", "html"]), null, ' ')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Exampe of axis result :
You can check it here:http://www.freeformatter.com/xml-to-json-converter.html
Before my fix it did not work for me.