JSON, XML, other format
Last updated
Was this helpful?
Last updated
Was this helpful?
Number: a signed decimal number that may contain a fractional part and may use exponential , but cannot include non-numbers such as . The format makes no distinction between integer and floating-point. JavaScript uses a for all its numeric values, but other languages implementing JSON may encode numbers differently.
: a sequence of zero or more characters. Strings are delimited with double-quotation marks and support a backslash syntax.
: either of the values true
or false
: an of zero or more values, each of which may be of any type. Arrays use notation with comma-separated elements.
: a collection of where the names (also called keys) are strings. Objects are intended to represent , where each key is unique within an object. Objects are delimited with and use commas to separate each pair, while within each pair the colon ':' character separates the key or name from its value.
: an empty value, using the word null
is allowed and ignored around or between syntactic elements (values and punctuation, but not within a string value). Four specific characters are considered whitespace for this purpose: , , , and . In particular, the must not be generated by a conforming implementation (though it may be accepted when parsing JSON). JSON does not provide syntax for
access: x = myObj.cars[0];
for (i in myObj.cars) {
x += myObj.cars[i];
}
for (i = 0; i < myObj.cars.length; i++) {
x += myObj.cars[i];
}
JavaScript function JSON.parse()
to convert text into a JavaScript object:var obj = JSON.parse('{ "name":"John", "age":30, "city":"New York"}');
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();
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();
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;
var myObj = {name: "John", age: 31, city: "New York"};
var myJSON = JSON.stringify(myObj);
window.location = "demo_json.php?x=" + myJSON;
var myJSON = '{"name":"John", "age":31, "city":"New York"}';
var myObj = JSON.parse(myJSON);
document.getElementById("demo").innerHTML = myObj.name;
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.
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.
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.
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 has to be parsed with an XML parser. JSON can be parsed by a standard JavaScript function.
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 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
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;
« 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:
is the de-facto standard, especially in developing RESTful web services. JSON won against its antagonist (SOAP) without a battle, but it didn’t prevent the development of alternatives like , or . In being thorough, we should also mention JSON compression (sometimes called “JSONC"), and , a binary-encoded serialization of JSON-like documents