将JSON对象解压缩并重命名为不同的格式
我正在从Foursquare API请求场地数据,但不会以geoJSON格式返回。我之前没有使用JSON,我也不知道如何处理这个问题。
我是否会遍历该对象并构建一个必要的对象值的JavaScript array
?如何使用相同的键选择所有值?是否可以从JSON响应中删除特定值并根据需要重命名其他值?这里最好的方法是什么?
下面我已经发布了我想要实现的输入和所需输出。
INPUT
{
"meta": {
"code": 200,
"requestId": "57c63303498e78d449981c2c"
},
"response": {
"venues": [{
"id": "430d0a00f964a5203e271fe3",
"name": "Brooklyn Bridge Park",
"location": {
"address": "Main St",
"crossStreet": "Plymouth St",
"lat": 40.70303245363086,
"lng": -73.99389265510275
}
}, {
"id": "51eabef6498e10cf3aea7942",
"name": "Brooklyn Bridge Park - Pier 2",
"contact": {},
"location": {
"address": "Furman St",
"crossStreet": "Brooklyn Bridge Park Greenway",
"lat": 40.69957016220183,
"lng": -73.99793274204788
}
}]
}
}
OUTPUT
[{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [-73.99389265510277, 40.703032453630854]
},
"properties": {
"id": "430d0a00f964a5203e271fe3",
"name": "Brooklyn Bridge Park",
"location": {
"address": "Main St",
"crossStreet": "Plymouth St",
"lat": 40.703032453630854,
"lng": -73.99389265510277
}
}
}, {
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [-73.9979327420479, 40.69957016220184]
},
"properties": {
"id": "51eabef6498e10cf3aea7942",
"name": "Brooklyn Bridge Park - Pier 2",
"location": {
"address": "Furman St",
"crossStreet": "Brooklyn Bridge Park Greenway",
"lat": 40.69957016220184,
"lng": -73.9979327420479
}
}
}]
回答如下:
您可以通过将响应保存到变量中来完成此操作。别忘了JSON.parse
吧。然后,您可以使用Array#map
方法将其转换为您自己的格式。
let obj = {
"meta": {
"code": 200,
"requestId": "57c63303498e78d449981c2c"
},
"response": {
"venues": [{
"id": "430d0a00f964a5203e271fe3",
"name": "Brooklyn Bridge Park",
"location": {
"address": "Main St",
"crossStreet": "Plymouth St",
"lat": 40.70303245363086,
"lng": -73.99389265510275
}
}, {
"id": "51eabef6498e10cf3aea7942",
"name": "Brooklyn Bridge Park - Pier 2",
"contact": {},
"location": {
"address": "Furman St",
"crossStreet": "Brooklyn Bridge Park Greenway",
"lat": 40.69957016220183,
"lng": -73.99793274204788
}
}]
}
};
let res = obj.response.venues.map((venue) => {
let o = {};
o.type = "feature";
o.geometry = {
type: "Point",
coordinates: [venue.location.lng, venue.location.lat]
};
o.properties = venue;
return o;
});
console.log(res);