JSON object and JSON string conversion methods

Source: Internet
Author: User
Tags string to json tojson

In the process of web data transfer, JSON is transmitted in the form of text, which is a lightweight type of string, while the client generally uses JS to manipulate the JSON object that is received, so the conversion between JSON object and JSON string and parsing of JSON data are key.

First clear 2 concepts such as:

JSON string:

var str1 = ' {' name ': ' Deyuyi ', ' sex ': ' Man '} ';

JSON object:

var str2 = {"Name": "Deluyi", "Sex": "Man"};

It is easy to understand:

JSON objects are formats that can be manipulated directly using jquery, such as the ability to point out properties (methods) in C # with objects (class names).

The JSON string is just a string, a whole, without intercepting the data stored in it, can not be used directly, unless you only want to alert () him;

One, JSON string converted to JSON object

To use the above str1, you must first convert to a JSON object using the following method:

A:eval function

The Eval function can directly convert a string that is inherently compliant or approximately in JSON format to a JSON object, using the following methods:

eval (' (' + str + ') '); Where Str is the string that satisfies the description of this title

    Convert from JSON string to JSON object
    var str= ' {' name ': ' John '} ';    var obj = eval (' (' + str + ') ');     alert (obj.name);    var str2= "{' name ': ' John '}";    var obj2 = eval (' (' + str2 + ') ');     alert (obj2.name);    var str3= "{name: ' John '}";    var obj3 = eval (' (' + STR3 + ') ');     alert (obj3.name);

The result "John" will be output.

The Eval method can convert the following standard and non-standard format strings:

   var str= "{' name ': ' John '}";   var str2= ' {' name ': ' John '} ';   var str3= "{name: ' John '}";

See the download package in this example: jquerydemo1.html

B:parsejson function

Another function that converts a standard string to a JSON object is Parsejson (), using a method such as Jquery.parsejson (str)//Where STR is the string that satisfies this title description

    Convert from JSON string to JSON object
    var str= ' {' name ': ' John '} ';    var obj = Jquery.parsejson (str)    alert ("1" + obj.name);

The result "John" will be output.

This method only supports the standard format: var str= ' {' name ': ' John '} ';

See the download package in this example: jquerydemo2.html

C:json.parse function

There is also a function that converts a standard string to a JSON object that is Json.parse (), used in such a way as json.parse (str)//Where STR is the string that satisfies the description of this title

        var str = ' {' name ': ' Mady ', ' Age ': ' "} ';        var obj = json.parse (str);        alert (obj.name);

The result "John" will be output.

This method only supports the standard format: var str= ' {' name ': ' John '} ';

See the download package in this example: jquerydemo3.html

The above results are consistent, all output names, such as:

Special Note: If obj is originally a JSON object, then using the eval () function after conversion (even if multiple conversions) is a JSON object, but there is a problem with the Parsejson () function (throwing a syntax exception).

D:other Way

If you can't help but want to make mistakes, very much want to parse non-standard, irregular strings, such as:

      {name:mady,age:23}

Or

      {name: ' Mady ', age:23}

As well as other types of illegal formats that you can think of that are inherently correct, then there is an extension library to solve

Jquery-json Extension Library

Here: http://code.google.com/p/jquery-json/

This library is used to extend JQuery, which extends two functions for JSON use:toJSON and Parsejson

The ToJSON function is used to serialize a normal JavaScript object into a JSON object.

The Parsejson function is used to serialize a normal JavaScript object into a JSON object too.

      
      
      
      
      
      
      alert (Obj2.plugin);

The above code executes results such as:

See the download package in this example: jquerydemo5.html

Second, convert the JSON object to a string

You can use tojsonstring () or global method json.stringify () to convert a JSON object to a JSON string.

For example:

var last=obj.tojsonstring (); Convert a JSON object to a JSON character

Or

var last=json.stringify (obj); Convert a JSON object to a JSON character

alert (last);

III. parsing Read JSON

When we convert a string to a JSON object in various ways, we parse him.

As the above example:

      var str2 = {"Name": "Mady", "Sex": "Man"};

You can read it like this:

      alert (str2.name);//and C # go straight to the point ...

Eject "Mady".

The JSON we encounter is rarely so simple, such as a bit more complex JSON objects such as:

      var str={"Getuserpostbyidresult": {"Age": "$", "ID": "2server", "Name": "Mady"}};

Parsing by:

      Alert (str. Getuserpostbyidresult.name);//I'll do it a few more times.

Pop up: "Mady".

A little more complicated like:

      var data= "{root: [{' name ': ' 6200 ', ' value ': ' 0 '}, {' name ': ' 6101 ', ' value ': ' Xa '}, {' name ': ' 6102 ', ' value ': ' Beijing '}, {' Name ': ' 6103 ', ' value ': ' Haerbin '}]} ";

If you want to be singled out, parse by:

      alert (dataobj.root[0].name);

Eject: "6200".

If you want to pick a group, parse it by:

      $.each (Dataobj.root, function (index, item) {            $ ("#info"). Append (                    "<div>" +index+ ":" + item.name + "</ Div> "+                     " <div> "+index+": "+ item.value +" </div>

Where this "#info" is the ID of a div. Input results such as:

See the download package in this example: jquerydemo4.html

Note: In this example, if you want to use a different conversion function, change the single quotation mark in the string to double quotation marks, and the inner number to single quotation marks.

This article all code: click to download

JSON object and JSON string conversion methods

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.