JSON, XML, other format

JSON's basic data types are:

Looping Through an Array

access: x = myObj.cars[0];

Looping Through an Array

for (i in myObj.cars) {

x += myObj.cars[i];

}

for (i = 0; i < myObj.cars.length; i++) {

x += myObj.cars[i];

}

Parsing JSON

JavaScript function JSON.parse() to convert text into a JavaScript object:var obj = JSON.parse('{ "name":"John", "age":30, "city":"New York"}');

JSON From the Server

Use the XMLHttpRequest to get data from the server:

var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var myObj = JSON.parse(this.responseText); document.getElementById("demo").innerHTML = myObj.name; } }; xmlhttp.open("GET", "json_demo.txt", true); xmlhttp.send();

Array as JSON

When using the JSON.parse() on a JSON derived from an array, the method will return a JavaScript array, instead of a JavaScript object.

var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var myArr = JSON.parse(this.responseText); document.getElementById("demo").innerHTML = myArr[0]; } }; xmlhttp.open("GET", "json_demo_array.txt", true); xmlhttp.send();

JSON.stringify()

Use the JavaScript function JSON.stringify() to convert it into a string.

var obj = { name: "John", age: 30, city: "New York" };

var myJSON = JSON.stringify(obj);

myJSON is now a string, and ready to be sent to a server:

var arr = [ "John", "Peter", "Sally", "Jane" ]; var myJSON = JSON.stringify(arr); document.getElementById("demo").innerHTML = myJSON;

JSON Applications

JSON-RPC

AJAJ

Sending Data

var myObj = {name: "John", age: 31, city: "New York"};

var myJSON = JSON.stringify(myObj);

window.location = "demo_json.php?x=" + myJSON;

Receiving Data

var myJSON = '{"name":"John", "age":31, "city":"New York"}';

var myObj = JSON.parse(myJSON);

document.getElementById("demo").innerHTML = myObj.name;

JSONP​

JSONP is a method for sending JSON data without worrying about cross-domain issues.

JSONP does not use the XMLHttpRequest object.

JSONP uses the <script> tag instead.

Use JSONP (JSON with Padding) as a means to prevent CORS requests to happen

Failed to load resource: Origin * is not allowed by Access-Control-Allow-Origin.

HTTP GET only

The JSONP way is only applicable to HTTP GET requests, no other method is supported. This is logical since the <script> tag can only make HTTP GET requests anyway. And this is precisely what we have leveraged earlier.

No error handling

Typically when working with AJAX requests we can see the error body returned by the API, however, using JSONP we either get a CORS error or we are faced with a 404 error. Either way, it's incredibly difficult to debug errors when using JSONP.

Vulnerability

JSONP exposes multiple vulnerabilities - it assumes excessive trust, it also further exposes CSRF (Cross-Site Request Forgery) vulnerabilities.

All in all, it is best not to use JSONP.

Now we have two Node.js processes - one is an API server that runs on port 3000 and the HTTP server that runs on port 8080. Due to the rules behind CORS, these are considered to be two separate entities, and therefore the browser is going to block accessing resources.

XML

XML has to be parsed with an XML parser. JSON can be parsed by a standard JavaScript function.

JSON is Like XML Because

  • Both JSON and XML are "self describing" (human readable)

  • Both JSON and XML are hierarchical (values within values)

  • Both JSON and XML can be parsed and used by lots of programming languages

  • Both JSON and XML can be fetched with an XMLHttpRequest

JSON is Unlike XML Because

  • JSON doesn't use end tag

  • JSON is shorter

  • JSON is quicker to read and write

  • JSON can use arrays

XML is much more difficult to parse than JSON. JSON is parsed into a ready-to-use JavaScript object.

For AJAX applications, JSON is faster and easier than XML:

Using XML

  • Fetch an XML document

  • Use the XML DOM to loop through the document

  • Extract values and store in variables

Using JSON

  • Fetch a JSON string

  • JSON.Parse the JSON string

Storing Data

When storing data, the data has to be a certain format, and regardless of where you choose to store it, text is always one of the legal formats.

JSON makes it possible to store JavaScript objects as text.

Storing data in local storage

// Storing data: myObj = {name: "John", age: 31, city: "New York"}; myJSON = JSON.stringify(myObj); localStorage.setItem("testJSON", myJSON); // Retrieving data: text = localStorage.getItem("testJSON"); obj = JSON.parse(text); document.getElementById("demo").innerHTML = obj.name;

What is MessagePack?

« MessagePack is an efficient binary serialization format. It lets you exchange data among multiple languages like JSON. But it’s faster and smaller ». To start using MessagePack we need to convert our application objects into MessagePack format: this process is called serialization, while the reverse process is called deserialization. The following example can help us better understand what we’re talking about. Consider this simple JSON:

JSONarrow-up-right is the de-facto standard, especially in developing RESTful web services. JSON won against its antagonist XMLarrow-up-right (SOAP) without a battle, but it didn’t prevent the development of alternatives like Google’s Protocol Buffersarrow-up-right, Apache Avroarrow-up-right or MessagePackarrow-up-right. In being thorough, we should also mention gziparrow-up-right JSON compression (sometimes called “JSONC"), and BSONarrow-up-right, a bin­ary-en­coded seri­al­iz­a­tion of JSON-like doc­u­ments

Last updated