如何使用JavaScript将以下内容转换为对象列表。
数据:
{"_id":{"$oid":"5d96f2d3db90fded9f3fa2d1"},"name":"Audi","price":52642},{"_id":{"$oid":"5d96f2dedb90fded9f3fa2d2"},"name":"Mercedes","price":57127},{"_id":{"$oid":"5d96f304db90fded9f3fa2d3"},"name":"Skoda","price":9000},{"_id":{"$oid":"5d96f368db90fded9f3fa2d4"},"name":"Volvo","price":29000},{"_id":{"$oid":"5d96f370db90fded9f3fa2d5"},"name":"Bentley","price":350000},{"_id":{"$oid":"5d96f378db90fded9f3fa2d6"},"name":"Citroen","price":21000},{"_id":{"$oid":"5d96f37fdb90fded9f3fa2d7"},"name":"Hummer","price":41400},{"_id":{"$oid":"5d96f389db90fded9f3fa2d8"},"name":"Volkswagen","price":21600}
当我对数据进行typeof运算时,我得到了字符串。我想做的是创建一个列表,其中包含每个对象的条目。我尝试了JSON.parse,但是花括号之间的逗号错误。谢谢。
答案 0 :(得分:1)
对于该特定字符串-逗号分隔的JSON对象-您可以将其包装在数组括号[]
中并进行解析:
var data = `{"_id":{"$oid":"5d96f2d3db90fded9f3fa2d1"},"name":"Audi","price":52642},{"_id":{"$oid":"5d96f2dedb90fded9f3fa2d2"},"name":"Mercedes","price":57127},{"_id":{"$oid":"5d96f304db90fded9f3fa2d3"},"name":"Skoda","price":9000},{"_id":{"$oid":"5d96f368db90fded9f3fa2d4"},"name":"Volvo","price":29000},{"_id":{"$oid":"5d96f370db90fded9f3fa2d5"},"name":"Bentley","price":350000},{"_id":{"$oid":"5d96f378db90fded9f3fa2d6"},"name":"Citroen","price":21000},{"_id":{"$oid":"5d96f37fdb90fded9f3fa2d7"},"name":"Hummer","price":41400},{"_id":{"$oid":"5d96f389db90fded9f3fa2d8"},"name":"Volkswagen","price":21600}`;
var parsed = JSON.parse(`[${data}]`);
然后parsed
将是8个条目的数组:
[
{
"_id": {
"$oid": "5d96f2d3db90fded9f3fa2d1"
},
"name": "Audi",
"price": 52642
},
{
"_id": {
"$oid": "5d96f2dedb90fded9f3fa2d2"
},
"name": "Mercedes",
"price": 57127
},
{
"_id": {
"$oid": "5d96f304db90fded9f3fa2d3"
},
"name": "Skoda",
"price": 9000
},
...