JavaScript string of string to json two ways

  • 2020-06-22 23:29:17
  • OfStack

The first way:

Use the js function eval();

testJson = eval (testJson); Is the wrong way to convert.

The transformation of the right way to add () : testJson = eval (" (" + testJson + ") ");

eval() is very fast, but it can compile and execute any javaScript program, so there are security issues. Using eval(). The source must be trustworthy. You need to use the more secure json parser. When the server is not strictly coded in json or if the input is not strictly validated, it is possible to provide an invalid json or to carry a dangerous script that executes in eval(), releasing malicious code.

js code:


  function ConvertToJsonForJs() {
            //var testJson = "{ name: ' Jack Bauer ', age: 16 }";( support )
            //var testJson = "{ 'name': ' Jack Bauer ', 'age': 16 }"; (support)
            var testJson = '{ "name": " Jack Bauer ", "age": 16 }';
            //testJson=eval(testJson);// Wrong conversion
            testJson = eval("(" + testJson + ")");
            alert(testJson.name);
        }

The second method USES the ES30en.parseJSON () method, which requires the json format to conform to the json format

jquery.parseJSON()

js: code


  function ConvertToJsonForJq() {
            var testJson = '{ "name": " Jack Bauer ", "age": 16 }';
            // I don't know
            //'{ name: " Jack Bauer ", age: 16 }' (name No double quotation marks are used )
            //"{ 'name': " Jack Bauer ", 'age': 16 }"(name Use single quotes )
            testJson = $.parseJSON(testJson);
            alert(testJson.name);
        }


Related articles: