Example details JSON data format and JSON format data field string conversion _javascript tips

Source: Internet
Author: User
Tags readable

JSON (JavaScript Object notation) is a lightweight data interchange format. JSON uses a completely language-independent text format that makes JSON an ideal data exchange language. Easy for people to read and write, but also easy to machine parsing and generation.

Basic structure

JSON is constructed in two structures:

1. Collection of name/value pairs (A collection of name/value pairs). In different languages, it is understood as objects (object), records (record), structure (struct), dictionaries (dictionary), hash tables (hash table), a list of keys (keyed list), or associative arrays (associative Array).

2. List of values (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 to a string, which can then be easily passed between functions, or pass a string from a WEB client to a server-side program in an asynchronous application. This string looks a little odd, but JavaScript is easy to explain, and JSON can represent a more complex structure than name/value pairs. For example, you can represent arrays and complex objects, not just simple lists of keys and values.

Represents a name/value pair

In the simplest form, you can use JSON to represent "name/value pairs": {"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 reflects its value. First, you can create records that contain multiple name/value pairs, such as:


In terms of syntax, this is not a great advantage compared to name/value pairs, but in this case JSON is easier to use and more readable. For example, it is clear that the above three values are part of the same record; curly braces make these values a bit of a connection.

Represents an array

When you need to represent a set of values, JSON not only improves readability, but it also reduces complexity. For example, suppose you want to represent a list of people. In XML, many start and end tags are required, and if you use a typical name/value pair (like the name/value pairs that you see in previous articles in this series), you must either create a proprietary data format or modify the key name to form Person1-firstname.
If you use JSON, you only need to group together multiple records with curly braces:

{"People": [ 
{"FirstName": "Brett", "LastName": "McLaughlin", "email": "AAAA"}, 
{"FirstName": "Jason", "Lastna Me ":" Hunter "," email ":" BBBB "}, 
{" FirstName ":" Elliotte "," LastName ":" Harold "," email ":" CCCC "} 

It's not hard to understand. In this example, there is only one variable named people, and the value is an array of three entries, each of which is a record of one person, including first, last name, and e-mail address. The preceding example shows how to combine records into a single value in parentheses. 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", "l Astname ":" Hunter "," email ":" BBBB "}, 
{" FirstName ":" Elliotte "," LastName ":" Harold "," email ":" CCCC "} 
"Authors": [ 
{"FirstName": "Isaac", "LastName": "Asimov", "Genre": "Science Fiction"}, 
{"FirstName": "Tad", "LA Stname ":" 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 be different between the main entries (programmers, authors, and musicians). JSON is completely dynamic, allowing you to change the way the data is represented in the middle of the JSON structure.

There are no predefined constraints to follow when working with JSON-formatted data. So, in the same data structure, you can change the way that you represent the data, and you can even represent the same thing in different ways.

Format application

Once you have the JSON format, it's easy to use it in JavaScript. JSON is the native format of JavaScript, which means that processing JSON data in JavaScript does not require any special APIs or toolkits.

Assigning JSON data to a variable

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

var people = {"Programmers": [{"FirstName": "Brett", "LastName": "McLaughlin", "email": "AAAA"}, 
{"FirstName": "Ja Son "," LastName ":" Hunter "," email ":" BBBB "}, 
{" FirstName ":" Elliotte "," LastName ":" Harold "," email ":" CCCC "} 
"authors": [ 
{"FirstName": "Isaac", "LastName": "Asimov", "Genre": "Science Fiction"}, 
{"FirstName": "T  Ad "," 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 JSON-formatted data that you saw earlier. But that's not enough, because the way the data is accessed doesn't seem obvious.

accessing data

Although it doesn't look obvious, the long string above is actually just an array, and after you put the array in a JavaScript variable, you can easily access it. In fact, you just use dot notation to represent an array element. So, to access the last name of the first entry in the programmers list, just use the following code in JavaScript:


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

Here are several examples of using the same variable.

People.authors[1].genre//Value is "fantasy" 
people.musicians[3].lastname//Undefined. This is refers to the fourth entry, and there isn ' t one 

With this syntax, you can work with any JSON-formatted data without using any additional JavaScript toolkits or APIs.

modifying JSON data

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


After you convert a string to a JavaScript object, you can modify the data in the variable like this.

Convert back to String

Of course, if you can't easily convert an object back to the text format mentioned in this article, all data modifications are not of much value. This conversion is also simple in JavaScript:


That'll do it! You now get a text string that you can use anywhere, for example, as a request string in an Ajax application.

More importantly, you can convert any JavaScript object to JSON text. It is not possible to handle only variables that were previously assigned with a JSON string. In order to convert an object named MyObject, you only need to perform the same form of command:


This is the biggest difference between JSON and other data formats discussed in this series. If you use JSON, simply call a simple function, you can get the formatted data, you can use it directly. For other data formats, you need to convert between the raw data and the formatted data. Even if you use an API such as Document object Model, which provides a function to convert your data structure to text, you need to learn the API and use the object of the API, rather than using native JavaScript objects and syntax.

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

Conceptual comparisons

Comparison of JSON and XML


JSON and XML are equally readable, with a simple syntax and a canonical label that makes it difficult to distinguish between the winners and losers.


XML is inherently extensible, of course, and there is nothing XML can extend, but JSON does not. But JSON is at home in JavaScript and can store JavaScript composite objects with an unmatched advantage of XML.

Coding Difficulty

XML has a wealth of coding tools, such as dom4j, Jdom, and so on, and JSON has the tools provided. Without tools, it is believed that skilled developers can write the desired XML document and JSON string as quickly as possible, but there are many more structured characters in the XML document.

Decoding difficulty

There are two ways to parse XML:

One is through the document model parsing, that is, through the parent tag index a set of tags. For example: Xmldata.getelementsbytagname ("TagName"), but this is to be used in the knowledge of the document structure in advance, not a generic encapsulation.

Another approach is to traverse the nodes (document and ChildNodes). This can be done by recursion, but the parsed data is still in a different form and often does not meet the predetermined requirements.

It must be difficult to parse any such scalable structural data.

The same is true of JSON. If you knew the JSON structure in advance, it would be wonderful to use JSON for data delivery, and you could write code that was practical and visually readable. If you're a purely front-desk developer, you'll love json very much. But if you're an application developer, you don't like it, after all, XML is the real structured markup language for data delivery.

It would be a nightmare to parse JSON without knowing the structure of JSON. With time and effort, the code becomes redundant and the results are unsatisfactory. However, this does not affect many foreground developers to choose JSON. Because of the tojsonstring () in json.js, you can see the string structure of the JSON. Of course not using this string, this is still a nightmare. When people who use JSON see this string, the JSON structure is clear and it's easier to manipulate JSON.

The above is the parsing of XML and JSON in JavaScript only for data transfer. In JavaScript sites, JSON is, after all, home combat, and its advantages are certainly far superior to XML. If you store JavaScript composite objects in JSON and don't know their structure, I'm sure many programmers are crying to parse JSON as well.

Instance comparison

Both XML and JSON use structured methods to mark data, and here's a simple comparison.

Some provinces and cities in China are represented by XML as follows:

<?xml version= "1.0" encoding= "Utf-8"?> 
<name> China </name> 
< province> 
<name> Heilongjiang </name> 
<city> Harbin </city> 
<city > Daqing </city> 
<name> Guangdong </ name> 
<city> Guangzhou </city> 
<city> shenzhen </city> 
<city > Zhuhai </city> 

The following is represented in JSON:

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

The readability of the encoding, XML has obvious advantages, after all, human language is more close to such a descriptive structure. JSON reads more like a block of data, and it's a bit confusing to read. However, the language we read is precisely what is suitable for machine reading, so the index of JSON is available. Province[0].name can read the value of "Heilongjiang".

In the handwriting difficulty of coding, XML is still more comfortable, so it is good to read and write. However, the character JSON written out is significantly less. When you remove blank tables and line-wrapping, JSON is a dense, useful data, while XML contains many repetitive markup characters.

JSON Online checksum tool

The JSON format replaces XML as a great convenience for network transport, but without a glance at XML, especially when JSON data is long, we get bogged down in tedious data-node lookups.
But a Chinese online tool Bejson has brought a cool breeze to many programmers.

function Introduction

1. JSON format checksum
A lot of people who get JSON data have no way of determining whether the JSON data format is correct, small or multiple, and the program can't parse it, and this feature will help you do the JSON-formatted checksum.

2. JSON view

Presumably many programmers will encounter when looking for a node, will find that if directly to a row of data, even know which location, but also a node to the bottom of a node to find, in case of an inattentive again have to start looking for trouble.

With this feature, all JSON data becomes a view format, at a glance, how many arrays are under what objects, and how many objects are under an array.

This function is very practical. Not only has the view function but also has the format, the compression, the escape, the verification function. It's very strong anyway.

3. Compression escape

When programmers write JSON-statement test cases, they often test them to make it easier to write a JSON string directly, but are stuck in endless double quotes escaping trouble. This feature set compression, escape in one, let you write test cases, as a duck to fish.

4. JSON Online Editor

If your current computer happens to not have the editor you're familiar with, this feature will meet your needs if you want to make data modifications to a node of the JSON data you get.

5. Send JSON data online

As you all know, JSON uses most of the development of Web projects, then you have to test whether an interface can accurately accept the JSON data, then you have to write a page to send a JSON string, repeat this thing. With this feature turned out, you can get rid of the write test page, because this feature can send the specified JSON data to the specified URL, convenient.

6. JSON coloring

Many people are writing documents, always want the document can be clear, but the face of white background black word JSON data always do not mind, use this function, all the keywords will be colored, data structure at a glance.

7. Json-xml and Mutual transfer

As the name suggests, converting JSON-formatted data into XML format, or XML-formatted data into JSON format, is not a problem.

JSON Format data field strings convert instance code to each other

The string and JSON format data can be converted to each other, of course, there is a real need for this, and here is an instance of the conversion at both ends.

A. JSON format data is converted to a string:

var arr=[{id: ' id ', Name: ' Spring '},{id: ' Id2 ', Name: ' Jane '}; 

To use the Json.stringify () function, you need to implement a reference Json2.js file, which can be downloaded in Baidu search.
Output result: "[{ID: ' id ', Name: ' Spring '},{id: ' Id2 ', Name: ' Jane '}]"

Two. String converted to JSON format data:

var str= ' [{ID: ' id ', Name: ' Spring '},{id: ' Id2 ', Name: ' Jane '}] '; 

Output result: [{ID: ' id ', Name: ' Spring '},{id: ' Id2 ', Name: ' Jane '}]

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.