我正在解析一些当前写成JavaScript变量的数据,但我想将其转换为有效的JSON,以便我可以解析它。这是变量的样子:
var machines = [{
category: "Category 1",
items: [{
name: "Test 1",
description: "Lorem Ipsum"
}, {
name: "Test 2",
description: "Lorem Ipsum"
}]
}, {
category: "Category 2",
items: [{
name: "Test 3",
description: "Lorem Ipsum"
}, {
name: "Test 4",
description: "Lorem Ipsum"
}]
}
];
我知道我必须删除var machines =
部分,但除此之外我还不确定如何制作这个有效的JSON。
答案 0 :(得分:1)
您必须使用原生的 JSON.stringify() 方法。
这是一个有用的 DEMO :
var machines = [{
category: "Category 1",
items: [{
name: "Test 1",
description: "Lorem Ipsum"
}, {
name: "Test 2",
description: "Lorem Ipsum"
}]
}, {
category: "Category 2",
items: [{
name: "Test 3",
description: "Lorem Ipsum"
}, {
name: "Test 4",
description: "Lorem Ipsum"
}]
}];
var json = JSON.stringify(machines);
console.log(json);
答案 1 :(得分:0)
通过JSON.stringify()
。
var machines = [{
category: "Category 1",
items: [{
name: "Test 1",
description: "Lorem Ipsum"
}, {
name: "Test 2",
description: "Lorem Ipsum"
}]
}, {
category: "Category 2",
items: [{
name: "Test 3",
description: "Lorem Ipsum"
}, {
name: "Test 4",
description: "Lorem Ipsum"
}]
}];
var json = JSON.stringify(machines);
console.log(json);