Home > Web Front-end > JS Tutorial > How to convert object to json format

How to convert object to json format

php中世界最好的语言
Release: 2018-04-24 17:26:41
Original
5644 people have browsed it

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

data type

)

var obj = {name: "中国", age: 5000};//->普通格式的对象
var jsonObj = {"name": "中国", "age": 5000};//->JSON格式的对象 (只要把普通对象的属性名用""(不能是'')包起来,这样的格式就是我们JSON格式的对象)
var data = [
{name: "", age: ""},
{name: "", age: ""}
];//->普通的
二维数组
Copy after login
var jsonData = [
{"name": "", "age": ""},
{"name": "", "age": ""}
];//->JSON格式的数据
Copy after login

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}
];
Copy after login
var str = JSON.stringify(data);//->'[{"name":"李四","age":48},{"name":"张三","age":84}]'
console.log(JSON.parse(str));
Copy after login

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);
Copy after login

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!

Recommended reading:

How to convert the format after ajax obtains json data


Methods for converting JSON strings and JSON objects into each other Summarize


The 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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template