JS JSON转对象
1. 什么是JSON
JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,它以文本形式表示结构化数据,可被多种编程语言解析和生成。JSON格式的数据易于阅读和编写,也易于解析和生成。
JSON采用键值对的方式来表示数据,数据由逗号分隔,键值对由冒号分隔。JSON中支持的数据类型有:
- 字符串(字符串必须使用双引号)
- 数字
- 对象(使用花括号{}表示)
- 数组(使用方括号[]表示)
- 布尔值(true或false)
- 空值(null)
下面是一个JSON的示例:
{
"name": "John",
"age": 30,
"isStudent": true,
"pets": [
"dog",
"cat"
],
"address": {
"street": "123 Main St",
"city": "New York"
}
}
2. JSON字符串转对象
在JavaScript中,可以通过JSON.parse()
方法将JSON字符串转换为JavaScript对象。
const jsonStr = '{"name":"John","age":30,"isStudent":true,"pets":["dog","cat"],"address":{"street":"123 Main St","city":"New York"}}';
const jsonObj = JSON.parse(jsonStr);
console.log(jsonObj.name); // Output: John
console.log(jsonObj.age); // Output: 30
JSON.parse()
方法会返回一个与JSON字符串对应的JavaScript对象。
3. JSON对象转字符串
在JavaScript中,可以通过JSON.stringify()
方法将JavaScript对象转换为JSON字符串。
const jsonObj = {
name: "John",
age: 30,
isStudent: true,
pets: ["dog", "cat"],
address: {
street: "123 Main St",
city: "New York"
}
};
const jsonStr = JSON.stringify(jsonObj);
console.log(jsonStr); // Output: {"name":"John","age":30,"isStudent":true,"pets":["dog","cat"],"address":{"street":"123 Main St","city":"New York"}}
JSON.stringify()
方法会返回一个与JavaScript对象对应的JSON字符串。
4. 使用Reviver函数转换特殊类型
当JSON中包含日期、正则表达式等特殊类型时,默认情况下会被转换为字符串。可以通过使用Reviver
函数来对特殊类型进行处理。
const jsonStr = '{"date":"2022-01-01T00:00:00.000Z","regex":"/^\\d+/"}';
const jsonObj = JSON.parse(jsonStr, (key, value) => {
if (key === "date") {
return new Date(value);
}
if (key === "regex") {
const match = value.match(/^\/(.*)\/(.*?)/);
return new RegExp(match[1], match[2]);
}
return value;
});
console.log(jsonObj.date instanceof Date); // Output: true
console.log(jsonObj.regex instanceof RegExp); // Output: true
在Reviver
函数中,可以根据键名判断是否需要进行特殊类型的转换,然后返回相应的值。
5. 错误处理
当JSON字符串不符合JSON格式时,解析会抛出异常,可以使用try...catch
语句来捕获异常并进行错误处理。
const invalidJsonStr = '{"name":"John","age":30,}';
try {
const jsonObj = JSON.parse(invalidJsonStr);
console.log(jsonObj);
} catch (error) {
console.error("Error parsing JSON:", error.message);
}
输出:
Error parsing JSON: Unexpected token } in JSON at position 25
6. 运行结果
const jsonStr = '{"name":"John","age":30,"isStudent":true,"pets":["dog","cat"],"address":{"street":"123 Main St","city":"New York"}}';
const jsonObj = JSON.parse(jsonStr);
console.log(jsonObj.name); // Output: John
console.log(jsonObj.age); // Output: 30
const jsonObj = {
name: "John",
age: 30,
isStudent: true,
pets: ["dog", "cat"],
address: {
street: "123 Main St",
city: "New York"
}
};
const jsonStr = JSON.stringify(jsonObj);
console.log(jsonStr); // Output: {"name":"John","age":30,"isStudent":true,"pets":["dog","cat"],"address":{"street":"123 Main St","city":"New York"}}
const jsonStr = '{"date":"2022-01-01T00:00:00.000Z","regex":"/^\\d+/"';
const jsonObj = JSON.parse(jsonStr, (key, value) => {
if (key === "date") {
return new Date(value);
}
if (key === "regex") {
const match = value.match(/^\/(.*)\/(.*?)/);
return new RegExp(match[1], match[2]);
}
return value;
});
console.log(jsonObj.date instanceof Date); // Output: true
console.log(jsonObj.regex instanceof RegExp); // Output: true
const invalidJsonStr = '{"name":"John","age":30,}';
try {
const jsonObj = JSON.parse(invalidJsonStr);
console.log(jsonObj);
} catch (error) {
console.error("Error parsing JSON:", error.message);
}
输出:
John
30
{"name":"John","age":30,"isStudent":true,"pets":["dog","cat"],"address":{"street":"123 Main St","city":"New York"}}
true
true
Error parsing JSON: Unexpected token } in JSON at position 25