Javascript method to convert json string and object: 1. Convert json to object, code is [var obj = eval('(' str ')')]; 2. Convert object to json, code It is [var str=obj.toJSONString()].
The operating environment of this tutorial: Windows 7 system, JavaScript version 1.8.5, DELL G3 computer.
Javascript method to convert json string and object:
Method 1: json.js to convert json and object to each other
In order to process JSON data conveniently, JSON provides json.js package and json.js free download address.
Convert json to object
//json转换为对象 var obj = eval('(' + str + ')'); 或者 var obj = str.parseJSON(); //json字符串转换为对象 或者 var obj = JSON.parse(str); //json字符串转换为对象
Note: If obj is originally a JSON object, then after conversion using the eval() function (even if it is converted multiple times) it will still be a JSON object, but using parseJSON( ) function will have questions after processing (throwing a syntax exception).
Convert object to json
//对象转成json 可以运用 toJSONString()或者JSON.stringify()将JSON对象转化为JSON字符串。 var str=obj.toJSONString(); //将对象转成json 或者 var last=JSON.stringify(obj); //将对象转成json
Above, except for the eval() function that comes with js, many other methods come from the json.js package. The new version of JSON modifies the API and injects both JSON.stringify() and JSON.parse() functions into the built-in objects of Javascript. The former becomes Object.toJSONString(), and the latter becomes String. parseJSON(). If you are prompted that toJSONString() and parseJSON() cannot be found, it means that your json package version is too low.
Method 2: jQuery.json implements conversion between json and objects
jQuery.json is a plug-in of jQuery that can easily realize objects and objects Conversion between JSON strings. It can serialize JavaScript objects, values, strings and arrays to JSON strings, and convert JSON strings to JavaScript. Free download address.
Convert object to json
//对象转成json var thing = {plugin: 'jquery-json', version: 2.3};//js对象 var str = $.toJSON(thing);//转换为json,结果: '{"plugin":"jquery-json","version":2.3}'
Convert json to object
//json转成对象 var obj= $.evalJSON(str); var name=obj.plugin;//js对象.属性,结果: "jquery-json" var version =obj.version;//结果: 2.3
Related free learning recommendations:javascript video tutorial
The above is the detailed content of How to convert json string and object in javascript. For more information, please follow other related articles on the PHP Chinese website!