我有一个像这样的大型json数据集:
{
"10001": {
"coords": [
"40.753793,-74.007026/40.750272,-74.00828",
"40.751445,-74.00143/40.752055,-74.000975",
"40.751439,-73.99768/40.752723,-73.99679"
],
"meta": {
"city": "New York",
"state": "NY",
"latCenter": 40.71,
"lngCenter": -73.99
}
},
"10002": {
"coords": [
"40.714069,-73.997504/40.709181,-73.996222/40.709485,-73.994022"
],
"meta": {
"city": "New York",
"state": "NY",
"latCenter": 40.71,
"lngCenter": -73.99
}
},
and so on....
}
我需要在"key" : "value"
类别中添加新的"meta"
数据。我尝试使用JSON.parse
将其转换为JavaScript对象,但它不起作用。它说JSON格式不正确。甚至在转换之后,如何通过循环实际访问元部分并在那里添加新值,保留旧的格式和数据?
答案 0 :(得分:1)
const data = {
"10001": {
"coords": [
"40.753793,-74.007026/40.750272,-74.00828",
"40.751445,-74.00143/40.752055,-74.000975",
"40.751439,-73.99768/40.752723,-73.99679"
],
"meta": {
"city": "New York",
"state": "NY",
"latCenter": 40.71,
"lngCenter": -73.99
}
},
"10002": {
"coords": [
"40.714069,-73.997504/40.709181,-73.996222/40.709485,-73.994022"
],
"meta": {
"city": "New York",
"state": "NY",
"latCenter": 40.71,
"lngCenter": -73.99
}
}
};
// inject key "hello" with value "world"
Object.keys(data).forEach(key => Object.assign(data[key].meta, { "hello": "world" }));
console.log(data);
答案 1 :(得分:0)
您应该使用Object.keys(object)
方法:
var obj={
"10001": {
"coords": [
"40.753793,-74.007026/40.750272,-74.00828",
"40.751445,-74.00143/40.752055,-74.000975",
"40.751439,-73.99768/40.752723,-73.99679"
],
"meta": {
"city": "New York",
"state": "NY",
"latCenter": 40.71,
"lngCenter": -73.99
}
},
"10002": {
"coords": [
"40.714069,-73.997504/40.709181,-73.996222/40.709485,-73.994022"
],
"meta": {
"city": "New York",
"state": "NY",
"latCenter": 40.71,
"lngCenter": -73.99
}
}
}
var keys=Object.keys(obj);
for(i=0;i<keys.length;i++){
obj[keys[i]]["meta"]["key"]=0;
}
console.log(obj);