Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

The method of turning strings into jsons in JavaScript


May 08, 2021 JSON



There are four main ways to turn strings to jason in JavaScript, as detailed below:

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 s eval ("" s testJson s");

eval() is very fast, but he can compile and execute any javaScript program, so there are security issues. I n use of eval(). T he source must be trustworthy. A more secure johnson parser is required. If the server is not strictly coded in json or if the input is not strictly validated, it is possible to provide invalid johnson or contain dangerous scripts, execute scripts in eval() and release malicious code.

js code:

The code is as follows:

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 requires a high level of json format, which must conform to the json format

jquery.parseJSON()

js: Code

The code is as follows:

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


The third way: Use Fusion to convert

js: Code

The code is as follows:

var jsonStr = '{"userName": "tiu","userAge": 26,"isMale": true}';
var json = (new Function("return " + jsonStr))();

You can see that the principle is to stitch the js code string, and then use Fusion to create an anonymous method and then call it!


Fourth way: use JSON global object, but unfortunately the version below IE8 does not have this object, if you do not consider compatible with the IE8 version of JSON global object is a very useful thing

The code is as follows:

var jsonStr = '{"userName": "tiu","userAge": 26,"isMale": true}';
var json = JSON.parse(jsonStr);
var str = JSON.stringify(json);