Home  >  Article  >  Web Front-end  >  Summary of the method of converting string to json in JS

Summary of the method of converting string to json in JS

php中世界最好的语言
php中世界最好的语言Original
2018-04-25 15:26:183100browse

This time I will bring you a summary of the stringconversion method to json in JS. What are the notes for converting string to json in JS? The following is a practical case. Let’s take a look. one time.

The first way:

Using the 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 anyjavaScript 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:

 function ConvertToJsonForJs() {
            //var testJson = "{ name: '小强', age: 16 }";(支持)
            //var testJson = "{ 'name': '小强', 'age': 16 }";(支持)
            var testJson = '{ "name": "小强", "age": 16 }';
            //testJson=eval(testJson);//错误的转换方式
            testJson = eval("(" + testJson + ")");
            alert(testJson.name);
        }

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

jquery.parseJSON()

js:code

 function ConvertToJsonForJq() {
            var testJson = '{ "name": "小强", "age": 16 }';
            //不知道
            //'{ name: "小强", age: 16 }' (name 没有使用双引号包裹)
            //"{ 'name': "小强", 'age': 16 }"(name使用单引号)
            testJson = $.parseJSON(testJson);
            alert(testJson.name);
        }

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website !

Recommended reading:

Using jquery to dynamically traverse Json object properties and values ​​​​detailed explanation

jQuery ajax uses the get() function to read Detailed explanation of steps on the page

The above is the detailed content of Summary of the method of converting string to json in JS. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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