Methods of JSON parsing summary _javascript tips

Source: Internet
Author: User
Tags eval

Recently, the project has always been transferred to the interface, not deep understanding is very confused, so simple to clean up and convenient for future search.

"String conversion to Object"

parse is used to parse out a JSON object from a string, such as
var str = ' {' Name ': ' Demo ', ' Age ': ' 22 '} '

Results

Json.parse (str)
Object
Age: "22"
Name: "Demo"
__proto__: Object

1.eval (' (' + str + ') '); the//eval () method executes the string (possibly the JS script) dynamically, which can easily cause system security problems.

var str= ' {' name ': ' John '} ';
var obj = eval (' (' + str + ') '); 

2.parseJSON (str)

var str= ' {' name ': ' John '} ';
var obj = Jquery.parsejson (str)

3.json.parse (str)

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

4.jquery-json Extension Library download:http://code.google.com/p/jquery-json/

"Convert object to String"

stringify () is used to parse out strings from an object, such as
var a = {A:1,b:2}

Results

Json.stringify (a)
• "{" A ": 1," B ": 2}"

You can use the 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); Converts a JSON object to JSON character
alert (last);

The above is a small set to introduce the JSON parsing method Summary of all the narration, I hope to help everyone, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.