Home > Article > Web Front-end > How to convert javascript to json string
How to convert javascript to json string: 1. Use the "eval()" method, syntax "eval("(" array name")")"; 2. Use "jquery.parseJSON()" Method, syntax "jquery.parseJSON(array name)".
The operating environment of this tutorial: Windows 7 system, JavaScript version 1.8.5, Dell G3 computer.
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 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 it does not strictly validate the input, it is possible to provide invalid json or contain dangerous scripts, execute the script in eval(), and release malicious 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 way: using the jquery.parseJSON() method has relatively high requirements on the format of json and must comply with the json format
jquery.parseJSON()
function ConvertToJsonForJq() { var testJson = '{ "name": "小强", "age": 16 }'; //'{ name: "小强", age: 16 }' (name没有使用双引号包裹) //"{ 'name': "小强", 'age': 16 }"(name使用单引号) testJson = $.parseJSON(testJson); alert(testJson.name); }
【Recommended learning: javascript video tutorial】
The above is the detailed content of How to convert javascript to json string. For more information, please follow other related articles on the PHP Chinese website!