Example Description: Conversion of JSON data format and json data domain strings _ javascript skills

Source: Internet
Author: User
Tags convert string to json string to json
JSON (JavaScriptObjectNotation) is a lightweight data exchange format. JSON uses a language-independent text format. These features make JSON an ideal Data Exchange Language, JSON (JavaScript Object Notation), a lightweight data exchange format. JSON uses a language-independent text format. These features make JSON an ideal data exchange language. Easy for reading and writing, and easy for machine parsing and generation.

Infrastructure

JSON is constructed in two structures:

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

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

Basic example

Simply put, JSON can convert a set of data represented in a JavaScript object to a string, and then it can be easily passed between functions, alternatively, the string is transmitted from the Web Client to the server in an asynchronous application. This string looks a bit odd, but JavaScript can easily interpret it, And JSON can represent a more complex structure than "name/value pairs. For example, it can represent arrays and complex objects, not just a simple list of keys and values.

Name/value pair

In the simplest form, you can use the following JSON to represent "name/value pairs": {"firstName": "Brett "}
This example is very basic and actually takes more space than the equivalent plain text "name/value pair": firstName = Brett

However, when you concatenate multiple "name/value pairs", JSON will reflect its value. First, you can create records containing multiple "name/value pairs", such:

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

In terms of syntax, this is not a great advantage over "name/value pairs", but JSON is easier to use and more readable in this case. For example, it explicitly indicates that the above three values are part of the same record; curly braces make these values have a certain relationship.

Array

To represent a group of values, JSON not only improves readability, but also reduces complexity. For example, assume that you want to list a person's name. In XML, many start and end tags are required. If a typical name/value pair is used (like the name/value pair seen in the previous articles in this series ), you must either create a proprietary data format or change the key name to a person1-firstName.
If JSON is used, you only need to group multiple records with curly braces:

{ "people": [ { "firstName": "Brett", "lastName":"McLaughlin", "email": "aaaa" }, { "firstName": "Jason", "lastName":"Hunter", "email": "bbbb"}, { "firstName": "Elliotte", "lastName":"Harold", "email": "cccc" } ]} 

This is not hard to understand. In this example, there is only one variable named people. The value is an array containing three entries, each of which is a one-person record, including the name, last name, and email address. The preceding example demonstrates how to use parentheses to combine records into a value. Of course, you can use the same syntax to represent multiple values (each value contains multiple records ):

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

The most noteworthy here is that it can represent multiple values, and each value contains multiple values. However, you should also note that the actual name/value pairs in the record can be different between different primary entries (programmers, authors, and musicians. JSON is completely dynamic and allows you to change the data representation mode in the middle of the JSON structure.

When processing data in JSON format, there are no predefined constraints to be observed. Therefore, in the same data structure, you can change the way data is represented, or even express the same thing in different ways.

Format Application

After mastering the JSON format, it is easy to use it in JavaScript. JSON is a JavaScript native format, which means that no special API or toolkit is required to process JSON data in JavaScript.

Assign JSON data to a variable

For example, you can create a new JavaScript variable and assign a value to the JSON-format data string:

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

This is very simple; now people contains the data in JSON format as shown above. However, this is not enough, because the data access method does not seem obvious.

Access Data

Although it does not seem obvious, the long string above is actually an array. After you put this array into the JavaScript variable, you can easily access it. In fact, you only need to use the dot notation to represent array elements. Therefore, to access the first project name in the programmers list, you only need to use the following code in JavaScript:

people.programmers[0].lastName; 

Note that the array index starts from scratch. Therefore, this line of code first accesses the data in the people variable, then moves to the entry called programmers, and then to the first record ([0]). Finally, it accesses the value of the lastName key. The result is the string value "McLaughlin ".

The following are examples of 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, You can process data in any JSON format without using any additional JavaScript toolkit or API.

Modify JSON data

Just as you can access data with periods and parentheses, you can easily modify the data in the same way:

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

After converting a string to a JavaScript Object, you can modify the data in the variable as follows.

Convert back to string

Of course, if you cannot easily convert an object back to the text format mentioned in this article, all data modifications are of little value. In JavaScript, this conversion is also very simple:

String newJSONtext = people.toJSONString(); 

That's all! Now you can obtain a text string that can be used anywhere. For example, you can use it as a request string in an Ajax application.

More importantly, any JavaScript Object can be converted to JSON text. It is not only applicable to variables that are originally assigned values using JSON strings. To convert an object named myObject, you only need to execute the same command:

String myObjectInJSON = myObject.toJSONString(); 

This is the biggest difference between JSON and other data formats discussed in this series. If JSON is used, you only need to call a simple function to obtain formatted data and use it directly. For other data formats, the conversion between the original data and the formatted data is required. Even if you use an API like Document Object Model (which provides a function to convert your data structure to text), you also need to learn this API and use the Object of the API, instead of using native JavaScript objects and syntaxes.

The final conclusion is that if you want to process a large number of JavaScript objects, JSON is almost certainly a good choice, so that you can easily convert the data to a format that can be sent to the server-side program in the request.

Concept comparison

Comparison between JSON and XML

◆ Readability

The readability of JSON and XML is comparable. One side is a simple syntax and the other is a standard tag form, making it difficult to distinguish between the two.

◆ Scalability

XML is inherently highly scalable, and JSON is also available. Nothing is XML, but JSON cannot. However, JSON can store Javascript composite objects at the home site of Javascript, which has an incomparable advantage of xml.

◆ Encoding difficulty

XML has rich coding tools, such as Dom4j and JDom, and JSON also provides tools. Without tools, I believe that skilled developers can quickly write the desired xml document and JSON string. However, the xml document requires many more structural characters.

◆ Decoding difficulty

XML can be parsed in two ways:

One is to parse the document model, that is, index a group of tags through the parent tag. For example, xmlData. getElementsByTagName ("tagName"), but this method is used when the document structure is known in advance and cannot be encapsulated.

Another method is to traverse 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.

It is difficult to parse such extensible structure data.

The same is true for JSON. If you know the JSON structure in advance, it is amazing to use JSON for data transmission. You can write code that is very practical, beautiful, and readable. If you are a pure front-end developer, you will love JSON very much. However, if you are an application developer, you are not that fond of it. After all, xml is the real structured markup language for data transmission.

However, parsing JSON without knowing the JSON structure would be a nightmare. Code will become redundant, and the results will be unsatisfactory. However, this does not affect the choice of JSON by many front-end developers. Because toJSONString () in json. js can see the JSON string structure. Of course, this string is not used. This is still a nightmare. After a common JSON user sees this string, the JSON structure is very clear, making it easier to operate JSON.

The preceding section only parses the xml and JSON data transmitted in Javascript. In the Javascript field, JSON is a battle at home after all, and its advantage is of course far superior to xml. If Javascript composite objects are stored in JSON and do not know their structure, I believe many programmers are crying to parse JSON.

◆ Instance comparison

Both XML and JSON use structured methods to mark data. The following is a simple comparison.

XML is used to represent data of some provinces and cities in China as follows:

<? Xml version = "1.0" encoding = "UTF-8"?>
  
  
   
China
   
   
   
    
Heilongjiang
    
   
    
     
Harbin
     
    
     
Daqing
     
    
   
   
   
    
Guangdong
    
    
    
     
Guangzhou
     
    
     
Shenzhen
     
    
     
Zhuhai
     
    
   
  

JSON format:

{Name: "China", province: [{name: "Heilongjiang", cities: {city: ["Harbin", "Daqing"]}, {name: "Guangdong", cities: {city: ["Guangzhou", "Shenzhen", "Zhuhai"]}

Xml has obvious advantages in readability of coding. After all, human languages are closer to such descriptive structures. Json reads are more like a data block, which is hard to read. However, the obscure language we read is suitable for machine reading, so the value of "Heilongjiang" can be read through the json index. province [0]. name.

For the difficulty of coding handwriting, xml is still more comfortable. If you are good at reading, you can write well. However, the number of characters written in JSON is much less. Without blank tabulation and line breaks, JSON is the useful data, while xml contains many repeated markup characters.

JSON online verification tool

Preface
JSON format replaces xml to Facilitate network transmission, but xml is not clear at a glance, especially when json data is very long, we will fall into complicated and complex data node searches.
However, BeJson, an online tool from Chinese people, has brought a cool breeze to many programmers.

Features

1. JSON format Validation
After obtaining JSON data, many people cannot determine whether the JSON data format is correct or not. If there are few or more symbols, the program cannot be parsed, this function can help you verify the JSON format.

2. JSON View

Presumably, many programmers will find that when looking for a node, they will find that if there is no way to start directly targeting a row of data, even if they know the location, they will need to find one node and one node, if you don't have to worry about it, you have to start from scratch.

With this function, all JSON data is converted into a view format, which shows at a glance how many arrays are under an object and how many objects are under an array.

This function is very practical. Not only does the view function have the formatting, compression, escape, and validation functions. In short, it is very powerful.

3. Compression escape

When programmers write JSON statement test cases, they often write a JSON string for testing convenience, but they are in the trouble of endless double quotation marks escaping. This feature is a combination of compression and escape, allowing you to write test cases, such as fish.

4. JSON online editor

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

5. Send JSON data online

As we all know, the most common use of JSON is web project development. To test whether an interface can accurately accept JSON data, you must write a page to send a JSON string, we are doing 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 for convenience.

6. JSON coloring

Many people always want to see the document clearly when writing the document, but it doesn't matter whether the spirit of the JSON data is hard to be raised. With this function, all the keywords will be colored, the data structure is clear at a glance.

7. JSON-XML exchange

As the name suggests, it is no problem to convert data in JSON format into XML format or JSON format.

Instance code for converting data domain strings in json format

String and json format data can be converted to each other. Of course, this is a practical requirement. The following is an example of conversion between the two ends.

I. convert data in json format to a string:

var arr=[{id:'id',name:'Spring'},{id:'id2',name:'Jane'}]; var str=JSON.stringify(arr); 

To use the JSON. stringify () function, you need to reference the json2.js file, which can be downloaded by Baidu search.
Output result: "[{id: 'id', name: 'spring'}, {id: 'id2', name: 'Jane '}]"

Ii. Convert String to json format data:

var str="[{id:'id',name:'Spring'},{id:'id2',name:'Jane'}]"; var json=$.parseJSON(str); 

Output result: [{id: 'id', name: 'spring'}, {id: 'id2', name: 'jar'}]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.