March 3, 2017

JSON for Ajax

JSON is so much easier to work with in Javascript than XML. This makes it perfect for coding responses from AJAX-backed web services.

An example JSON data structure:

{

'projects':[

{'ID':'1','Type':'StrangeProject','Members':['Joe','Jim','Jane']},

{'ID':'2','Type':'NiceProject','Members':['Richard','John','Joe']}

]

}

And here's how to parse it in Javascript (myJSONData is a text string containing the above structure, e.g. lifted directly from the response text from an AJAX call):

var jsonData = eval('('+myJSONData+')');

And here's how to get the data out of it after parsing:

for (var projectIndex in jsonData['projects']) {

var project = jsonData['projects'][projectIndex];

var type = project['Type'];

for (var memberIndex in project['Members']) {

var member = project['Members'][memberIndex];

....

}

....

}

Dead easy really, and totally cross-platform compatible - no more putting in code to handle the different XML parsing techniques in different browsers.

Be warned though, because it uses eval() it is susceptible to hacking by insertion of malicious Javascript code into the values in the data structure. You'll need to make sure you have server- and client-side code to help protect against this, e.g. by escaping any dangerous symbols in values encoded in the text.

Topics: Ajax, Big data technology, Json, Shell scripting