Some questions about JSON

Source: Internet
Author: User
Tags array to string convert json array to string

JSON (JavaScript Object Notation)

is a lightweight data interchange format. It is based on a subset of ECMAScript. JSON takes a completely language-independent text format, but also uses a similar idiom to the C language family (c, C + +, C #, Java, JavaScript, Perl, Python, and so on). These features make JSON an ideal data exchange language. Easy to read and write, but also easy to machine parse and generate (typically used to improve network transfer rates).

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), recording (record), structure (struct), Dictionary (dictionary), hash table (hash table), keyed list (keyed list), or associative array (associative Array).

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

Basic example

Simply put, JSON can convert a set of data represented in a JavaScript object into a string, which can then be easily passed between functions, or in an asynchronous application passing a string from a WEB client to a server-side program. The string looks a bit odd, but JavaScript is easy to explain, and JSON can represent a more complex structure than a name/value pair. 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, a "name/value pair" can be represented by a JSON such as the following: {"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:

{"FirstName": "Brett", "LastName": "McLaughlin", "email": "AAAA"}

In terms of syntax, this has no significant advantage over name/value pairs, but in this case JSON is easier to use and more readable. For example, it makes it clear that the above three values are part of the same record, and that the curly braces make some of these values a connection.

Represents an array

When you need to represent a set of values, JSON not only improves readability, but 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 pair you see in the previous article in this series), you must create a proprietary data format or change the key name to a form such as Person1-firstname.

If you use JSON, you only need to group multiple records with curly braces together:

{"People": [

{"FirstName": "Brett", "LastName": "McLaughlin", "email": "AAAA"},

{"FirstName": "Jason", "LastName": "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 person's record with first name, last name, and e-mail address. The above example shows how to combine records into a single value with 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", "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. However, it should also be noted that the actual name/value pairs in the record can differ between the different main entries (programmers, authors, and musicians). JSON is completely dynamic, allowing changes in 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 you represent data, and you can even represent the same thing in different ways.

Format app

Once you've mastered the JSON format, it's easy to use it in JavaScript. JSON is a native JavaScript format, which means that working with 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 the JSON-formatted data string 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"}

] }

This is very simple; now people contains the JSON-formatted data you saw earlier. However, this is not enough, because the way data is accessed doesn't seem to be obvious.

accessing data

Although it doesn't seem obvious, the long string above is really just an array, and after you put the array into a JavaScript variable, it's easy to access. In fact, you simply represent the array element with a dot notation. 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 the array index is 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 a string value of "McLaughlin".

Here are a few 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 work with any JSON-formatted data without the need for 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:

People.musicians[1].lastname = "Rachmaninov";

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 the object cannot be easily converted back to the text format mentioned in this article, then all data modifications are not of much value. This conversion is also simple in JavaScript:

String Newjsontext = people.tojsonstring ();

It's all right! Now you get a text string that can be used anywhere, for example, you can use it as a request string in an Ajax application.

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

String Myobjectinjson = myobject.tojsonstring ();

This is the biggest difference between JSON and other data formats discussed in this series. If you use JSON, just 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 original data and the formatted data. Even if you use an API such as the 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 instead of 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 you can easily convert the data into a format that can be sent to the server-side program in the request.

Concept comparison

Comparison of JSON and XML

Readability

JSON and XML are comparable in readability, with simple syntax on one side and a canonical label on the other, which makes it difficult to distinguish between the winners and losers.

Scalability

XML is inherently well-extensible, and JSON, of course, has nothing to do with XML extension, and JSON does not. However, JSON in the JavaScript home combat, can store JavaScript compound object, with XML incomparable advantage.

Coding Difficulty

XML has a wealth of coding tools, such as dom4j, Jdom, and so on, and JSON also provides tools. Without tools, it is believed that skilled developers can quickly write the desired XML document and JSON string, but the XML document has many more characters on the structure.

Decoding difficulty

There are two ways to parse XML:

One is to parse through the document model, that is, to index a set of tags through the parent tag. For example: Xmldata.getelementsbytagname ("TagName"), but this is to be used in the case of pre-knowledge of the document structure, unable to do a generic encapsulation.

Another way is to traverse nodes (document and ChildNodes). This can be achieved through recursion, but the parsed data is still different form, often can not meet the pre-requirements.

It must be difficult to parse any such extensible structure data.

The same is true for JSON. If you know the JSON structure in advance, it is wonderful to use JSON for data passing, and you can write very useful, aesthetically readable code. If you are a purely front-desk developer, you will love json very much. But if you're an app developer, it's not like that, after all, XML is the real structured markup language for data transfer.

It's a nightmare to parse JSON without knowing the structure of the JSON. Time and effort not to say, the code will become redundant procrastination, the results are also unsatisfactory. However, this does not affect many foreground developers to choose JSON. Because toJSONString () in json.js, you can see the string structure of the JSON. Of course not using this string, it's still a nightmare. When people who use JSON see the string, the JSON structure is straightforward and the JSON is easier to manipulate.

The above is the parsing of XML and JSON only for data passing in JavaScript. In JavaScript, JSON is a home battle, 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 a lot of programmers are crying and parsing json as well.

Instance comparison

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

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

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

<country>

<name> China </name>

<province>

<name> Heilongjiang </name>

<cities>

<city> Harbin </city>

<city> Daqing </city>

</cities>

</province>

<province>

<name> Guangdong </name>

<cities>

<city> Guangzhou </city>

<city> Shenzhen </city>

<city> Zhuhai </city>

</cities>

</province>

</country>

This is represented by 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 closer to such a description structure. JSON reads more like a block of data, which is more puzzling to read. However, the unintelligible language that we read is precisely the right machine to read, so through the JSON index. Province[0].name will be able to read "Heilongjiang" this value.

The encoding of handwriting difficulty, the XML is still comfortable, good read of course is good to write. However, the character JSON written is significantly less. With blank tabulation and line wrapping, JSON is a dense and useful data, and XML contains many duplicate tag characters.

JSON Online Validation Tool

Objective

The JSON format takes the place of XML for the convenience of network transmission, but without the obvious XML, especially when the JSON data is very long, we get into the tedious and complex data node lookups.

But a Chinese online tool, Bejson, brings a cool breeze to many programmers.

Feature Introduction

1. JSON format check

A lot of people after the JSON data, there is no way to determine whether the JSON data format is correct, whether less or more symbols to cause the program can not be resolved, this function can help you to complete the JSON format verification.

2. JSON view

Presumably a lot of programmers will encounter when looking for a node, will find that if directly to a row of data can not start, even if you know which location, but also a node of a node down to find, in case an inattentive and have to start from scratch to find the trouble.

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

This feature is very useful. There are not only view functions, but also formatting, compression, escaping, and checking. It's very powerful anyway.

3. Compression escaping

Programmers write JSON statements to test cases, many times in order to facilitate the direct writing of a JSON string to do the test, but also into the endless double-quote escaping the trouble. This feature set compresses, escapes in one, lets you write the test case in a duck's time.

4. JSON Online Editor

If your current computer doesn't happen to have the editor you're familiar with, if you want to make data changes to a node of the JSON data you've got, this feature will meet your needs.

5. Send JSON data online

As you all know, JSON uses most of the Web project development, then you want to test whether an interface can accurately accept the JSON data, then you have to write a page to send a JSON string, repeating 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, conveniently.

6. JSON coloring

A lot of people in the writing document, always hope that the document can be clearly visible, but the face of the white black character JSON data is always not up to mind, using this function, all the keywords will be colored, data structure at a glance.

7. Json-xml Mutual Transfer

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

Category: JavaScript

/**

* Get the appropriate Java array from the JSON array

* Use of the ToArray () method under Jsonarray

* @param str

* @return

*/

public static object[] Getjsontoarray (String str) {

Jsonarray Jsonarray = Jsonarray.fromobject (str);

return Jsonarray.toarray ();

}

public static void Main (string[] args) {

Jsonarray jsonstrs = new Jsonarray ();

Jsonstrs.add (0, "cat");

Jsonstrs.add (1, "dog");

Jsonstrs.add (2, "bird");

Jsonstrs.add (3, "duck");

Object[] Obj=getjsontoarray (jsonstrs.tostring ());

for (int i=0;i<obj.length;i++) {

System.out.println (Obj[i]);

}

}

A Java array is obtained from a JSON array, which can be transformed, such as converting Jsonarray to string, long, double, integer, date, and so on.

The methods of GetString (index), Getlong (index), getdouble (index) and GetInt (index) under Jsonarray are respectively used.

Similarly, if you want to get the elements in a Java array, you only need to traverse the array.

Java Code Collection Code

/**

* Converts a JSON array to a long type

* @param str

* @return

*/

public static long[] Getjsontolongarray (String str) {

Jsonarray Jsonarray = Jsonarray.fromobject (str);

Long[] Arr=new long[jsonarray.size ()];

for (int i=0;i<jsonarray.size (); i++) {

Arr[i]=jsonarray.getlong (i);

System.out.println (Arr[i]);

}

return arr;

}

/**

* Convert JSON array to string type

* @param str

* @return

*/

public static string[] Getjsontostringarray (String str) {

Jsonarray Jsonarray = Jsonarray.fromobject (str);

String[] Arr=new string[jsonarray.size ()];

for (int i=0;i<jsonarray.size (); i++) {

Arr[i]=jsonarray.getstring (i);

System.out.println (Arr[i]);

}

return arr;

}

/**

* Convert JSON array to double type

* @param str

* @return

*/

public static double[] Getjsontodoublearray (String str) {

Jsonarray Jsonarray = Jsonarray.fromobject (str);

Double[] Arr=new double[jsonarray.size ()];

for (int i=0;i<jsonarray.size (); i++) {

Arr[i]=jsonarray.getdouble (i);

}

return arr;

}

/**

* Convert JSON array to date type

* @param str

* @return

*/

public static date[] Getjsontodatearray (String jsonstring) {

Jsonarray Jsonarray = Jsonarray.fromobject (jsonstring);

date[] Datearray = new date[jsonarray.size ()];

String datestring;

Date date;

SimpleDateFormat sdf=new SimpleDateFormat ("Yyyy-mm-dd");

for (int i = 0; i < jsonarray.size (); i++) {

datestring = jsonarray.getstring (i);

try {

Date=sdf.parse (datestring);

Datearray[i] = date;

} catch (Exception e) {

E.printstacktrace ();

}

}

return datearray;

}

public static void Main (string[] args) {

Jsonarray jsonlongs = new Jsonarray ();

Jsonlongs.add (0, "111");

Jsonlongs.add (1, "222.25");

Jsonlongs.add (2, New Long (333));

Jsonlongs.add (3, 444);

Long[] Log=getjsontolongarray (jsonlongs.tostring ());

for (int i=0;i<log.length;i++) {

System.out.println (Log[i]);

}

Jsonarray jsonstrs = new Jsonarray ();

Jsonstrs.add (0, "2011-01-01");

Jsonstrs.add (1, "2011-01-03");

Jsonstrs.add (2, "2011-01-04 11:11:11");

Date[] D=getjsontodatearray (jsonstrs.tostring ());

for (int i=0;i<d.length;i++) {

System.out.println (D[i]);

}

}

/* results are as follows:

* 111

* 222

* 333

* 444

*

* Sat Jan 00:00:00 CST 2011

* Mon Jan 00:00:00 CST 2011

* Tue Jan 00:00:00 CST 2011

*/

Some questions about JSON

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.