This time I will bring you a summary of thestringconversion method to json in JS. What are thenotesfor 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 anyjavaScriptprogram, 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 thejquery.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!