SoFunction
Updated on 2025-04-11

2 ways to convert string (string) to json in JavaScript

The first method:

Use 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. A safer json parser is required. In the server, the unstrictly encoded in json or if the input is not strictly verified, it is possible to provide invalid json or a dangerous script, execute the script in eval(), and release malicious code.

js code:

Copy the codeThe code is as follows:

  function ConvertToJsonForJs() {
//var testJson = "{ name: 'Xiaoqiang', age: 16 }";(support)
//var testJson = "{ 'name': 'Xiaoqiang', 'age': 16 }"; (Supported)
var testJson = '{ "name": "Xiaoqiang", "age": 16 }';
//testJson=eval(testJson);//Incorrect conversion method
            testJson = eval("(" + testJson + ")");
            alert();
        }

The second method uses the() method to have high requirements for json format and must comply with the json format.

()

js:code

Copy the codeThe code is as follows:

  function ConvertToJsonForJq() {
var testJson = '{ "name": "Xiaoqiang", "age": 16 }';
//have no idea
//'{ name: "Xiaoqiang", age: 16 }' (name is not wrapped in double quotes)
//"{ 'name': "Xiaoqiang", 'age': 16 }" (name uses single quotes)
            testJson = $.parseJSON(testJson);
            alert();
        }