2 ways to turn a string in JavaScript into JSON

Source: Internet
Author: User
Tags eval json

This article mainly introduces 2 methods of String (string) to JSON in JavaScript, two methods are using the JS function eval () and, using the Jquery.parsejson () method, the need for friends can refer to the

The first way:

Use the JS function eval ();

Testjson=eval (Testjson); Is the wrong way to convert.

The correct conversion method needs to be added (): Testjson = eval ("+ Testjson +"));

Eval () is very fast, but he can compile and execute any JavaScript program, so there are security issues. The eval () is used. The source must be trustworthy. You need to use a more secure JSON parser. If the server is not rigidly encoded in JSON or if the input is not rigorously validated, it is possible to provide invalid JSON or contain a dangerous script, execute the script in eval (), and release the malicious code.

JS Code:

The code is as follows:

function Converttojsonforjs () {

var Testjson = "{name: ' Cockroach ', age:16}";(support)

var Testjson = "{' name ': ' Cockroach ', ' Age ':}";(support)

var Testjson = ' {' name ': ' Cockroach ', ' age ': 16} ';

Testjson=eval (Testjson);//Wrong way of conversion

Testjson = eval ("+ Testjson +"));

alert (testjson.name);

}

The second way to use the Jquery.parsejson () method is to have a high format for JSON and must conform to the JSON format

Jquery.parsejson ()

JS: Code

The code is as follows:

function Converttojsonforjq () {

var Testjson = ' {' name ': ' Cockroach ', ' age ': 16} ';

I don't know

' {name: ' Cockroach ', age:16} ' (name is not wrapped with double quotes)

' {' name ': ' Cockroach ', ' age ': ' (name uses single quotes)

Testjson = $.parsejson (Testjson);

alert (testjson.name);

}

Related Article

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.