我试图从另一个js文件中获取json对象。我发现最终结果是字符串形式的json看起来像这样
"[{ "part": "Part1", "dwg": "ASAD" }, { "part": "Part2", "dwg": "B" }];"
如何转换为JSON对象?这是我的代码
var jsonData = $.get("/Scripts/dummy.js", function (data) {
console.log(data);
return data;
});
答案 0 :(得分:0)
使用JSON.stringify()。
var json = JSON.stringify(data);
答案 1 :(得分:0)
要将字符串转换为JSON对象,请使用JSON.parse:
var jsonObject = JSON.parse(jsonText);
var jsonData = $.get("/Scripts/dummy.js", function (data) {
console.log(data);
return JSON.parse(data);
});
答案 2 :(得分:0)
你需要的是JSON.parse():
var json = '[{ "part": "Part1", "dwg": "ASAD" }, { "part": "Part2", "dwg": "B" }]';
JSON.parse(json);
答案 3 :(得分:0)
首先,您需要从对象字符串中删除尾随;
并使用正确的单/双引号包装:
// Your string used all double quotes, replace the outermost quotes with single
// quotes as shown below. Also notice that the ; has been moved outside the
// string, semicolons are not permitted as part of JSON object strings
var x = '[{ "part": "Part1", "dwg": "ASAD" }, { "part": "Part2", "dwg": "B" }]';
然后使用JSON.parse()
返回有效的JSON对象:
JSON.parse(x);
=> [ { part: 'Part1', dwg: 'ASAD' },
{ part: 'Part2', dwg: 'B' } ]