JSON data format

JSON (JavaScript Object Notation) is a lightweight data interchange format. JSON is in a completely language-independent text format, and these features make JSON an ideal data-interchange language. Easy to read and write by humans, but also easy to parse and generate by machines.

basicly construct

JSON is constructed from two structures:

1. A collection of name/value pairs. In different languages, it is understood as an object, a record, a struct, a dictionary, a hash table, a keyed list, or an associative array array).

2. An ordered list of values. In most languages, it is understood as an array.

 

Basic example

Simply put, JSON converts a set of data represented in a JavaScript object into a string, which can then be easily passed between functions, or passed from a web client to a server in an asynchronous application terminal program. This string looks a little quirky, but JavaScript interprets it easily, and JSON can represent more complex structures than "name/value pairs". For example, arrays and complex objects can be represented, not just simple lists of keys and values.

Represents a name/value pair

In its simplest form, a "name/value pair" can be represented in JSON like this: { "firstName": "Brett" }

This example is very basic and actually takes up more space than the equivalent plain text "name/value pair": firstName=Brett

However, when multiple "name/value pairs" are strung together, JSON takes on its value. First, you can create records containing multiple "name/value pairs", such as:

{ "firstName": "Brett", "lastName":"McLaughlin", "email": "aaaa" }

Syntactically, this doesn't have a huge advantage over "name/value pairs", but JSON is easier to use and more readable in this case. For example, it makes it clear that the above three values ​​are all part of the same record; the curly braces make the values ​​somehow related.

represents an array

When it comes to representing a set of values, JSON can improve readability and reduce complexity. For example, suppose you want to represent a list of people's names. In XML, many opening and closing tags are required; if you use typical name/value pairs (like those seen in earlier articles in this series), then a proprietary data format must be established , or change the key name to something like person1-firstName.

If using JSON, just group multiple curly braced records together:

{ "people": [

{ "firstName": "Brett", "lastName":"McLaughlin", "email": "aaaa" },

{ "firstName": "Jason", "lastName":"Hunter", "email": "bbbb"},

{ "firstName": "Elliotte", "lastName":"Harold", "email": "cccc" }

]}

This is not difficult to understand. In this example, there is only one variable called people, and the value is an array of three entries, each of which is a record of a person, which contains the first name, last name, and email address. The above example shows how to use parentheses to combine records into a single value. Of course, multiple values ​​(each containing multiple records) can be represented using the same syntax:

{ "programmers": [

{ "firstName": "Brett", "lastName":"McLaughlin", "email": "aaaa" },

{ "firstName": "Jason", "lastName":"Hunter", "email": "bbbb" },

{ "firstName": "Elliotte", "lastName":"Harold", "email": "cccc" }

],

"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" }

] }

Most notable here is the ability to represent multiple values, each of which in turn contains multiple values. It should also be noted, however, that the actual name/value pairs in the record can vary between different main entries (programmers, authors, and musicians). JSON is completely dynamic, allowing changes in the way data is represented in the middle of the JSON structure.

There are no predefined constraints to obey when working with data in JSON format. So, within the same data structure, you can change the way you represent the data, and you can even represent the same thing differently.

 

format application

Once you master the JSON format, using it in JavaScript is straightforward. JSON is a JavaScript-native format, which means that processing JSON data in JavaScript does not require any special API or toolkit.

Assign JSON data to variable

For example, you can create a new JavaScript variable and assign a JSON-formatted string of data directly to it:

var people = { "programmers": [ { "firstName": "Brett", "lastName":"McLaughlin", "email": "aaaa" },

{ "firstName": "Jason", "lastName":"Hunter", "email": "bbbb" },

{ "firstName": "Elliotte", "lastName":"Harold", "email": "cccc" }

],

"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" }

] }

It's pretty simple; people now contains the JSON-formatted data we saw earlier. However, that's not enough, as it doesn't seem obvious how to access the data.

 

access data

Although it may not seem obvious, the long string above is really just an array; once you put this array into a JavaScript variable, you can easily access it. In fact, just use dot notation to represent array elements. So, to access the last name of the first entry in the programmers list, just use the following code in JavaScript:

people.programmers[0].lastName;

Note that array indices are zero-based. So, this line of code first accesses the data in the people variable; then moves to the entry called programmers, then moves to the first record ([0]); and finally, accesses the value of the lastName key. The result is the string value "McLaughlin".

Below are a few examples using the same variable.

people.authors[1].genre // Value is "fantasy"

people.musicians[3].lastName // Undefined. This refers to the fourth entry, and there isn't one

people.programmers[2].firstName // Value is "Elliotte"

With this syntax, any JSON-formatted data can be processed without using any additional JavaScript toolkits or APIs.

 

Modify JSON data

Just as data can be accessed with dots and parentheses, data can be easily modified in the same way:

people.musicians[1].lastName = "Rachmaninov";

After converting the string to a JavaScript object, the data in the variable can be modified like this.

 

convert back to string

Of course, all data modification is of little value if the object cannot be easily converted back to the text format mentioned in this article. This conversion is also simple in JavaScript:

String newJSONtext = people.toJSONString();

that's fine! You now have a text string that can be used anywhere, for example, as a request string in an Ajax application.

What's more, any JavaScript object can be converted to JSON text. Not only can handle variables that were originally assigned a JSON string. To convert an object named myObject, simply execute a command of the same form:

String myObjectInJSON = myObject.toJSONString();

This is the biggest difference between JSON and the other data formats discussed in this series. If using JSON, just call a simple function and get the formatted data ready to use. For other data formats, conversion between raw and formatted data is required. Even with an API like the Document Object Model (which provides functions to convert your own data structures to text), you need to learn the API and use the API's objects instead of using native JavaScript objects and syntax.

The bottom line is that if you're dealing with a lot of JavaScript objects, JSON is almost certainly a good choice, so that you can easily convert the data into a format that can be sent to a server-side program in a request.

 

Concept comparison

Comparison of JSON and XML

Readability

The readability of JSON and XML can be said to be comparable, with simple syntax on the one hand and standardized tag form on the other, it is difficult to tell the winner.

Scalability

XML is inherently extensible, and of course JSON does. There is nothing that XML can extensible, but JSON can't. However, JSON fights at home in Javascript and can store Javascript composite objects, which has incomparable advantages over xml.

Coding difficulty

XML has rich encoding tools, such as Dom4j, JDom, etc. JSON also has tools provided. Without tools, I believe that skilled developers can quickly write the desired xml document and JSON string, but the xml document needs a lot more structural characters.

Decoding difficulty

There are two ways to parse XML:

One is parsing through the document model, that is, indexing a set of tags through the parent tag. For example: xmlData.getElementsByTagName("tagName"), but this is to be used when the document structure is known in advance, and general encapsulation cannot be performed.

Another way is to iterate over the nodes (document and childNodes). This can be achieved through recursion, but the parsed data is still in different forms, and often cannot meet the pre-requirements.

Any such extensible structured data must be difficult to parse.

The same goes for JSON. If you know the JSON structure in advance, using JSON for data transfer is simply wonderful, and you can write very practical, beautiful and readable code. If you're a pure front-end developer, you'll love JSON. But if you are an application developer, not so fond of it, after all, xml is the real structured markup language for data transfer.

And parsing JSON without knowing its structure is a nightmare. Not to mention time-consuming and laborious, the code will become redundant and procrastinated, and the results obtained are not satisfactory. But this does not affect the choice of JSON by many front-end developers. Because toJSONString() in json.js can see the string structure of JSON. Certainly not using this string, which is still a nightmare. After seeing this string, people who use JSON often have a clear understanding of the structure of JSON, and it is easier to manipulate JSON.

The above is the parsing of xml and JSON only for data transfer in Javascript. In the Javascript field, JSON is the home field after all, and its advantages are of course far superior to xml. If JSON is stored in Javascript composite objects, and I don't know its structure, I believe that many programmers will also cry and parse JSON.

Example comparison

Both XML and JSON use structured methods to mark up data, so let's do a simple comparison.

The data of some provinces and cities in China are represented by XML as follows:

<?xml version="1.0" encoding="utf-8"?>

<country>

    <name>中国</name>

    <province>

        <name>Heilongjiang</name>

     <cities>

            <city>Harbin</city>

            <city>Daqing</city>

        </cities>

    </province>

    <province>

        <name>广东</name>

        <cities>

            <city>Guangzhou</city>

            <city>深圳</city>

            <city>Zhuhai</city>

        </cities>

    </province>

</country>

 

Expressed in JSON as follows:

{

{name:"China", province:[ { name:"Heilongjiang", cities:{ city:["Harbin","Daqing"] },

{name:"Guangdong", cities:{ city:["Guangzhou","Shenzhen","Zhuhai"] } 

}

The readability of encoding, xml has obvious advantages, after all, human language is closer to such a description structure. JSON reads more like a data block, and it is more confusing to read. However, the language that we read incomprehensible is precisely suitable for machine reading, so the value of "Heilongjiang" can be read through the json index .province[0].name.

In terms of the handwriting difficulty of coding, xml is still more comfortable, and it is easy to write if it is easy to read. However, the character JSON written out is significantly less. Without the blank tabs and line breaks, JSON is densely packed with useful data, while xml contains a lot of repeated markup characters.

 

JSON online verification tool

foreword

The JSON format has replaced xml and brought great convenience to network transmission, but it is not as clear as xml, especially when the json data is very long, we will be caught in the tedious and complex data node search.

But BeJson, an online tool of the Chinese, has brought a cool breeze to many programmers.

Function introduction

1. JSON format verification

After getting JSON data, many people have no way to judge whether the format of JSON data is correct or not, and whether there are few or more symbols and the program cannot be parsed. This function can just help everyone to complete the verification of JSON format.

2. JSON view

Presumably many programmers will encounter that when looking for a node, they will find that if they directly face rows of data, they can't start. Even if they know where they are, they still have to search down node by node. Start looking for trouble.

With this function, all JSON data will be transformed into a view format, and it is clear at a glance, how many arrays are under what objects, and how many objects are under an array.

This function is very useful. Not only the view function but also the formatting, compression, escaping, and verification functions. Anyway very powerful.

3. Compression escape

When programmers write JSON statement test cases, they often write a JSON string directly for testing for convenience, but they fall into the endless trouble of escaping double quotes. This feature set compression and escaping in one, allowing you to write test cases like a duck to water.

4. JSON Online Editor

If your current computer happens to not have an editor you are familiar with, this function can meet your needs if you want to modify data for a node of the JSON data you get.

5. Send JSON data online

We all know that JSON is mostly used in the development of web projects. If you want to test whether an interface can accurately accept JSON data, then you have to write a page to send JSON strings and do this repeatedly. With the emergence of this function, you can get rid of writing test pages, because this function can send the specified JSON data to the specified url, which is convenient.

6. JSON Coloring

When many people write a document, they always hope that the document can be seen at a glance, but it doesn't matter if you face JSON data with black characters on a white background.

7. JSON-XML conversion

As the name implies, it is not a problem to convert data in JSON format into XML format, or data in XML format into JSON format.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326381527&siteId=291194637