我的JSON数据有什么问题?
var myJSON = [
{"x":108, "y":58, "w":431, "h":23},
{"x":203, "y":121, "w":240, "h":47},
{"x":64, "y":183, "w":138, "h":9},
{"x":140, "y":208, "w":85, "h":7},
{"x":51, "y":225, "w":263, "h":135},
{"x":51, "y":376, "w":75, "h":7},
{"x":51, "y":393, "w":263, "h":123},
{"x":51, "y":532, "w":263, "h":112},
{"x":51, "y":655, "w":263, "h":112},
{"x":334, "y":183, "w":68, "h":9},
{"x":333, "y":508, "w":262, "h":112},
{"x":417, "y":645, "w":95, "h":7},
{"x":332, "y":664, "w":264, "h":103},
{"x":441, "y":488, "w":47, "h":7},
{"x":333, "y":508, "w":262, "h":112}
];
当我尝试解析var myObj = JSON.parse(myJSON);
时,我收到以下错误:
SyntaxError:JSON.parse:第1行第2列的意外字符 JSON数据
[了解更多]
答案 0 :(得分:3)
JSON.parse()
需要一个JSON字符串并将其解析/转换为一个对象。
JSON.stringify()
期望对象并将其字符串化/转换为JSON字符串。
您正在尝试使用JSON.parse()
来解析对象,这没有任何意义。
由于您的数据已经是一个对象(an array is an object),您可以立即将其分配给myObj
,跳过解析步骤:
var myObj = [
{"x":108, "y":58, "w":431, "h":23},
{"x":203, "y":121, "w":240, "h":47},
{"x":64, "y":183, "w":138, "h":9},
{"x":140, "y":208, "w":85, "h":7},
{"x":51, "y":225, "w":263, "h":135},
{"x":51, "y":376, "w":75, "h":7},
{"x":51, "y":393, "w":263, "h":123},
{"x":51, "y":532, "w":263, "h":112},
{"x":51, "y":655, "w":263, "h":112},
{"x":334, "y":183, "w":68, "h":9},
{"x":333, "y":508, "w":262, "h":112},
{"x":417, "y":645, "w":95, "h":7},
{"x":332, "y":664, "w":264, "h":103},
{"x":441, "y":488, "w":47, "h":7},
{"x":333, "y":508, "w":262, "h":112}
];
答案 1 :(得分:1)
JSON.parse
解析为javascript对象时, string
才有效。如果你已经有一个javasript对象(或数组),你不需要JSON.parse:
var myJSON = `[
{"x":108, "y":58, "w":431, "h":23},
{"x":203, "y":121, "w":240, "h":47},
{"x":64, "y":183, "w":138, "h":9},
{"x":140, "y":208, "w":85, "h":7},
{"x":51, "y":225, "w":263, "h":135},
{"x":51, "y":376, "w":75, "h":7},
{"x":51, "y":393, "w":263, "h":123},
{"x":51, "y":532, "w":263, "h":112},
{"x":51, "y":655, "w":263, "h":112},
{"x":334, "y":183, "w":68, "h":9},
{"x":333, "y":508, "w":262, "h":112},
{"x":417, "y":645, "w":95, "h":7},
{"x":332, "y":664, "w":264, "h":103},
{"x":441, "y":488, "w":47, "h":7},
{"x":333, "y":508, "w":262, "h":112}
]`;
console.log(JSON.parse(myJSON));

答案 2 :(得分:0)
您正在尝试将JSON对象解析为JSON对象,如果您的myJSON已经是对象,则不需要这样做。
如果将其存储为字符串,那么JSON.parse()
将非常有用。
答案 3 :(得分:0)
为什么要解析JSON对象?您确定不想将其转换为字符串格式(使用JSON.stringify())???
答案 4 :(得分:0)
JSON.parse()
方法解析JSON字符串,构造字符串描述的JavaScript值或对象。可以提供可选的reviver函数,以在返回结果对象之前对其执行转换。
var json = '{"result":true, "count":42}';
obj = JSON.parse(json);
console.log(obj.count);
// expected output: 42
console.log(obj.result);
// expected output: true