Web development , php , ajax , symfony, framework, zend
In: web resources
14 Apr 2011If you follow me on Twitter, you know that I’ve been working on a super top secret mobile application using Appcelerator Titanium. The experience has been great: using JavaScript to create easy to write, easy to test, native mobile apps has been fun. My mobile app connects to numerous social network APIs, some of which only provide an XML response. My mini “framework” uses JSON to dynamically create widgets so I’ve needed a way to turn XML into JSON. I found many solutions but none of them worked. After tweaking an existing function, I’ve found a solution that works great.
It’s important to point out that Titanium’s Titanium.XML.DOMDocument object implements DOM2-level structures. Here’s the magic XML to JSON code:
// Changes XML to JSON
function xmlToJson(xml) {
// Create the return object
var obj = {};
if (xml.nodeType == 1) { // element
// do attributes
if (xml.attributes.length > 0) {
obj["@attributes"] = {};
for (var j = 0; j < xml.attributes.length; j++) {
var attribute = xml.attributes.item(j);
obj["@attributes"][attribute.nodeName] = attribute.nodeValue;
}
}
} else if (xml.nodeType == 3) { // text
obj = xml.nodeValue;
}
// do children
if (xml.hasChildNodes()) {
for(var i = 0; i < xml.childNodes.length; i++) {
var item = xml.childNodes.item(i);
var nodeName = item.nodeName;
if (typeof(obj[nodeName]) == "undefined") {
obj[nodeName] = xmlToJson(item);
} else {
if (typeof(obj[nodeName].length) == "undefined") {
var old = obj[nodeName];
obj[nodeName] = [];
obj[nodeName].push(old);
}
obj[nodeName].push(xmlToJson(item));
}
}
}
return obj;
};
The major change I needed to implement was using attributes.item(j) instead of the attributes[j] that most of the scripts I found used. With this function, XML that looks like:
<ALEXA VER="0.9" URL="davidwalsh.name/" HOME="0" AID="="> <SD TITLE="A" FLAGS="" HOST="davidwalsh.name"> <TITLE TEXT="David Walsh Blog :: PHP, MySQL, CSS, Javascript, MooTools, and Everything Else"/> <LINKSIN NUM="1102"/> <SPEED TEXT="1421" PCT="51"/> </SD> <SD> <POPULARITY URL="davidwalsh.name/" TEXT="7131"/> <REACH RANK="5952"/> <RANK DELTA="-1648"/> </SD> </ALEXA>
…becomes workable JSON with the following structure:
{
"@attributes": {
AID: "=",
HOME: 0,
URL: "davidwalsh.name/",
VER: "0.9",
},
SD = [
{
"@attributes": {
FLAGS: "",
HOST: "davidwalsh.name",
TITLE: A
},
LINKSIN: {
"@attributes": {
NUM: 1102
}
},
SPEED: {
"@attributes": {
PCT: 51,
TEXT: 1421
}
},
TITLE: {
"@attributes": {
TEXT: "David Walsh Blog :: PHP, MySQL, CSS, Javascript, MooTools, and Everything Else",
}
},
},
{
POPULARITY: {
"@attributes": {
TEXT: 7131,
URL: "davidwalsh.name/"
}
},
RANK: {
"@attributes": {
DELTA: "-1648"
}
},
REACH: {
"@attributes": {
RANK = 5952
}
}
}
]
}
This function has been extremely useful in allowing me to quickly disregard XML and use JSON instead. The function works well when structuring attributes and arrays of nested child nodes. Keep this handy; at some point you may need to convert XML to JSON!
This blog delivers stylish and dynamic news for designers and web-developers on all subjects of design, ranging from: CSS, Ajax, Javascript, web design, graphics, typography, advertising & much more. Our goal is to help you communicate effectively on the web with an engaging website or functional interface.
13 Responses to Convert XML to JSON with JavaScript
who_is_jack_shit
April 27th, 2011 at 1:52 pm
Not got a favourite but use Peggle, Bejeweled Blitz, Sickapedia, MSN messenger, YAK the most.
Cost nothing as Ipone is jailbroken and got them from Installous.
NeveRetail PhoneStore
May 6th, 2011 at 7:33 pm
For which Market the iPhone or the Android Market, submitting something to the Android market is quite simple.
mkzx
May 12th, 2011 at 8:02 am
I don't understand what you mean by 'themes'.
For applications it will depend on which mobile platform you're targeting.
iphone is the biggy. The traditional way to develop for iphone is on a Mac, using Xcode as the environment and Objective C *sigh* as the language.
if you're targeting Android, traditionally you'll be coding in Java, (so use eclipse as your environment).
There are other devices out there of course, but I'm no expert on any of this.
If you're serious, I'd recommend a cross platform mobile engine. I've played with the Airplay SDK a little, and it seems really good – you can program in C++ and deploy to iphone, android, symbian and more. Also Unity supports android and iphone now (but is quite expensive, and is really just for games).
junysb3
May 21st, 2011 at 6:36 am
if you're using glassfish, then 1.9. though apart from the network code, i'm trying to keep the APIs as close as possible
The Conceited Bastard
May 21st, 2011 at 3:46 pm
shampoo
Andrew Johnson
May 29th, 2011 at 6:56 am
I will be updating Brompt.com to Drupal 7 very soon. I sure hope the D7 Aggregator.module heeds this advice—cause the old version was a big headache of DOMDocument bugginess.
Walter M
June 3rd, 2011 at 9:47 am
I think it is Java ME(Micro Edition) actually
WindowsPhoneFRA
June 3rd, 2011 at 3:01 pm
An app to improve access: This issue’s story about a new mobile phone ‘app’ concerns Access4All, an application …
SOCIAL MEDIA GURL
June 4th, 2011 at 6:23 pm
What is the best phone to use Google #Mobile Apps.? mobile sms mobile #cheap :
alanphillips78
June 8th, 2011 at 1:00 pm
I have a project being designed in *.stl or *.obj files and need them converted to a CAD application ISG Format *.lges or *.step files. Can you help Don (Budget: $30-$250 AUD, Jobs: Computer Security, FileMaker)
Gemma
June 8th, 2011 at 9:19 pm
The big stories at Verizon Developer Community Conference 2010 (VDCC) are APIs and VCAST Apps for Day 1. Opening keynote talks and panels explored a range of topics that are on the minds of all mobile app developers. Let’s take a closer look. Sponsor There’s an API for that When you consider that all the LBS startups today are still looking for precision in determining where the user might be, the Network API announcement at VDCC are both exciting and a cause to reflect further. Consider that when most developers think about fragmentation this is handset and device specific. Now, with the emergence of a RESTful equivalent API for the network means the notions of being carrier specific with your development choices as well. The initial RESTful network API areas will be location, SMS and MMS. It will be critical for developers to get certified quickly for access to make this worthwhile and vibrant. So does fragmentation really matter? The fragmentation question was posed on Day 1 during…
dpfw16
June 9th, 2011 at 8:39 pm
You are correct about the 10%- there is only about 10% of the energy gained going from one trophic level to the next (the other 90% is lost).
This is THE reason why there can't be unlimited levels in an ecosystem- it is MUCH TOO INEFFICIENT.
In a very short time, you reach a level (3 or 4 levels up) where you can't go higher, because there just isn't enough energy available. They would need to eat so much of the lower level that that level wouldn't exist and the whole ecosystem would pretty much collapse. So, that level won't happen at all.
YourSearchBuddy
June 12th, 2011 at 3:56 pm
#widgets Widget Interface: For a widget instance, a user agent must expose a unique object that implements the w…