Examples of two common ways in which js reads json

  • 2020-03-30 04:08:29
  • OfStack

Method 1: the most famous eval method in js


var strJson="{name:' Zhang SAN '}";//json
var obj=eval("("+strJson+")");//The converted json object
alert(obj.name);//json name

One thing to note about this method is:

Object expression {'name':' zhang SAN '} must be expanded with '()', otherwise


var strJSON = "{name:' Zhang SAN '}";
var obj = eval(strJSON);
alert(obj.constructor);//String constructor
alert(obj.name);//undefine

To generate an anonymous object, you must extend the object expression to an eval execution!

Method 2: function construction definition method returns


var strJSON = "{name:' Zhang SAN '}";//The resulting JSON
var obj = new Function("return" + strJSON)();//The converted JSON object
alert(obj.name);//json name


Related articles: