Two methods for converting string to json in JavaScript _ javascript skills

Source: Internet
Author: User
Tags string to json
This article mainly introduces two methods for converting string (string) to json in JavaScript, namely using js function eval () and jquery. parseJSON () method. For more information, see Method 1:

Use the js function eval ();

TestJson = eval (testJson); is the incorrect conversion method.

The correct conversion method requires adding (): testJson = eval ("(" + testJson + ")");

Eval () is very fast, but it can compile and execute any javaScript program, so there will be security issues. When using eval (). The source must be trustworthy. Use a safer json parser. If the server is not strictly encoded in json or if the input is not strictly verified, it is possible to provide invalid json or contain dangerous scripts and execute the script in eval, release malicious code.

Js code:

The code is as follows:


Function ConvertToJsonForJs (){
// Var testJson = "{name: 'xiaoqiang ', age: 16}"; (supported)
// Var testJson = "{'name': 'xiaoqiang ', 'age': 16}"; (supported)
Var testJson = '{"name": "Xiaoqiang", "age": 16 }';
// TestJson = eval (testJson); // The conversion method is incorrect.
TestJson = eval ("(" + testJson + ")");
Alert (testJson. name );
}


The second method is to use the jquery. parseJSON () method, which requires a high requirement on the json format and must comply with the json format.

Jquery. parseJSON ()

Js: code

The code is as follows:


Function ConvertToJsonForJq (){
Var testJson = '{"name": "Xiaoqiang", "age": 16 }';
// Unknown
// '{Name: "Xiaoqiang", age: 16}' (name is not enclosed in double quotation marks)
// "{'Name':" Xiaoqiang ", 'age': 16}" (single quotes are used for name)
TestJson = $. parseJSON (testJson );
Alert (testJson. name );
}

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.