I am parsing out some data that's written out as a JavaScript variable currently, but I would like to convert it to valid JSON so I can parse it out that way. Here's what the variable looks like:
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"
}]
}
];
I know I have to remove the var machines =
part, but besides that I'm not sure how to make this valid JSON.
You have to use native JSON.stringify() method.
Here's a working 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);
Pass it through 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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.