Home > Web Front-end > JS Tutorial > body text

2 ways to convert string to json in JavaScript_javascript skills

WBOY
Release: 2016-05-16 15:53:03
Original
1168 people have browsed it

First way:

Use js function eval();

testJson=eval(testJson); is the wrong 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. Using eval(). The source must be trustworthy. Need to use a more secure json parser. If the server does not strictly encode the json or if the input is not strictly validated, it is possible to provide invalid json or contain dangerous scripts, execute the script in eval(), and release malicious code.

js code:

Copy 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);//Wrong conversion method
             testJson = eval("(" testJson ")");
alert(testJson.name);
}

The second method uses the jquery.parseJSON() method, which has higher requirements on the format of json and must comply with the json format

jquery.parseJSON()

js:code

Copy code The code is as follows:

function ConvertToJsonForJq() {
              var testJson = '{ "name": "Xiaoqiang", "age": 16 }';
                    // Don’t know
​​​​​​ //'{ name: "Xiaoqiang", age: 16 }' (name is not wrapped in double quotes)
//"{ 'name': "Xiaoqiang", 'age': 16 }" (name uses single quotes)
              testJson = $.parseJSON(testJson);
alert(testJson.name);
}

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!