JSON, the product of the Post-XML era. When XML is widely accepted, people begin to notice the redundant data in XML, so some people are thinking about some XML variants, what kind of BinaryXML is, JSON is almost born in this age.
Let's first look at an XML:
<request> <firstName>Brett</firstName> <lastName>McLaughlin</lastName> <email>brett@newInstance.com</email></request>
In this XML file, each tag appears twice, and so much traffic is used. Moreover, China's network is better than Russia's wire network. Haha.
What does the corresponding JSON look like?
{ "firstName": "Brett", "lastName":"McLaughlin", "email": "brett@newInstance.com" }
In this way, the tag appears only once, saving some space. The name: value is displayed in pairs. Here is a complex example:
{ "people": [ { "firstName": "Brett", "lastName":"McLaughlin", "email": "brett@newInstance.com" }, { "firstName": "Jason", "lastName":"Hunter", "email": "jason@servlets.com" }, { "firstName": "Elliotte", "lastName":"Harold", "email": "elharo@macfaq.com" }]}
Use [] to enclose multiple tags under a tag. A friend with some basic knowledge should have read this introduction, and I will not continue to talk about it below, and there is nothing to say. Next, let's take a look at how to use JSON in JS.
JSON is a built-in data type of JS, so it can be parsed without any third-party files. It is more than N in Delphi, and regular expressions are not supported. JSON is not supported... ah. here is a JSON variable to see how to define it:
var people = { "programmers": [ { "firstName": "Brett", "lastName":"McLaughlin", "email": "brett@newInstance.com" }, { "firstName": "Jason", "lastName":"Hunter", "email": "jason@servlets.com" }, { "firstName": "Elliotte", "lastName":"Harold", "email": "elharo@macfaq.com" } ], "authors": [ { "firstName": "Isaac", "lastName": "Asimov", "genre": "science fiction" }, { "firstName": "Tad", "lastName": "Williams", "genre": "fantasy" }, { "firstName": "Frank", "lastName": "Peretti", "genre": "christian fiction" } ], "musicians": [ { "firstName": "Eric", "lastName": "Clapton", "instrument": "guitar" }, { "firstName": "Sergei", "lastName": "Rachmaninoff", "instrument": "piano" } ] }
How can I access the elements in it? In fact, this is equivalent to several combined arrays. We use subscript to access:
People. authors [1]. genre // "fantasy" people. musicians [3]. lastName // Undefined. there is no fourth element, people. programmers. [2]. firstName // "Elliotte" people. musicians [1]. lastName = "Rachmaninov"; // modify the value of an element.
Finally, let's take a look at the JSON element conversion string:
String newJSONtext = people.toJSONString();
Note that in JS, any Obj has the toJSONString () method and can be converted to a JSON string.