Home > Article > Web Front-end > How to convert object to json format
This time I will show you how to convert objects into json format, and what are the things to note when converting objects into json format. The following is a practical case, let's take a look.
1. What is JSON?
JSON is just a data format (it is not a new
var obj = {name: "中国", age: 5000};//->普通格式的对象 var jsonObj = {"name": "中国", "age": 5000};//->JSON格式的对象 (只要把普通对象的属性名用""(不能是'')包起来,这样的格式就是我们JSON格式的对象) var data = [ {name: "", age: ""}, {name: "", age: ""} ];//->普通的 二维数组
var jsonData = [ {"name": "", "age": ""}, {"name": "", "age": ""} ];//->JSON格式的数据
2. The window browser object provides us with some methods for operating JSON format data->window. JSON
->stringify: Convert JSON format/normal format objects into JSON format string
->parse: Convert JSON format strings into JSON format objects
var data = [ {name: "李四", age: 48}, {name: "张三", age: 84} ];
var str = JSON.stringify(data);//->'[{"name":"李四","age":48},{"name":"张三","age":84}]' console.log(JSON.parse(str));
3. Regarding compatibility issuesThere is no JSON attribute under window in IE6 and IE7
console.log(window .JSON); ->How to convert a JSON format string into a JSON format object when the output result under IE6~7 is undefined
is incompatible? ->Use eval, but remember It is best to manually add parentheses on the left and right sides of the string
var str = '[{"name":"李四","age":48},{"name":"张三","age":84}]'; var data = eval("(" + str + ")");//->兼容的话我们使用JSON.parse(str) console.dir(data);
Recommended reading:
How to convert the format after ajax obtains json dataMethods for converting JSON strings and JSON objects into each other SummarizeThe above is the detailed content of How to convert object to json format. For more information, please follow other related articles on the PHP Chinese website!