Home >Web Front-end >JS Tutorial >Objects and JSON in JavaScript_Basics
Introduction
JSON is JavaScript Object Natation. It is a lightweight data exchange format that is very suitable for the interaction between the server and JavaScript.
JSON is a data exchange format, like XML and YAML, a way to transfer structured information between various languages. On the other hand, JavaScript objects are a data type in the JavaScript language, just like arrays in PHP, classes and structures in C.
Define JSON and javascript objects
When defining an object in a JavaScript program, the attribute name of the object can be enclosed in double quotes or not. If the attribute name contains special characters (such as!, if, etc.), double quotes must be added.
When defining JSON, the attribute name must be enclosed in double quotes.
Code example:
1. Define javascript object
javascript object converted to JSON
1. Convert javascript object to JSON
We can use javascript’s built-in function to convert javascript objects to JSON. This function is JSON.stringify().
Code example:
Parsing JSON in javascript
In older versions of JS, everyone usually uses the eval() function to parse JSON, but ECMAScript5 provides us with a new function JSON.parse() for parsing JSON.
The use of this function is relatively simple, you can try it yourself. When this function is applied to a JSON string, the JSON is converted into a JavaScript object. That is to say, when the typeof operator is used to view the type of the function, the returned value is Object.
Another thing to note is that this function is only supported after ECMAScript 5. If it is an older version of the browser, it may not support this function. The solution is to load a js file that implements this function, namely json2.js. If you are using the JQuery framework, jQuery.parseJSON(), this function calls the JSON.parse() method.
Regarding using the eval() method to parse JSON, this will be recorded after in-depth study.
A very important concept
As a front-end rookie, I often hear people say "JSON object", but in fact there is no concept of "JSON object". The real form of JSON is a string.