从URL解析JSON文件的各个部分以用于Mapbox



我正在尝试解析JSON的一部分,以便与Mapbox一起使用。下面是一个JSON文件示例:

{
"time":"06:00",
"location": [
{
"device_id": "019823123123123",
"geometry": {
"type": "point",
"coordinates": [
-4.19635681,
20.19492493,
-12.282
]
}
}
]
}

这是代码的一部分:

async function getLocation(updateSource) {
try {
const response = await fetch(
'http://localhost/data.json', {
method: 'GET'
}
);
const {

coordinates // <<--- THIS IS MY PROBLEM, HOW DO I FETCH THIS PART OF JSON?

// var longitude = location[1].geometry.coordinates[0] <<--- I ALSO TRIED THIS BUT NOT LUCK
// var latitude = location[1].geometry.coordinates[1] <<--- I ALSO TRIED THIS BUT NOT LUCK

} = await response.json()

map.flyTo({
center: [longitude, latitude], // <<-- AND CONVERT IT TO THIS FORM?
essential: true

});

如何将坐标数组放入单独的经度/纬度中?谢谢

看起来您正在尝试使用Destructuring赋值。

location是一个对象的数组,它具有geometry属性,它具有坐标属性,这是一个数组,您只需要该数组的前两个元素。

const response = {
"time":"06:00",
"location": [
{
"device_id": "019823123123123",
"geometry": {
"type": "point",
"coordinates": [
-4.19635681,
20.19492493,
-12.282
]
}
}
]
}
const {
location: [
{
geometry: {
coordinates: [ lat, lng ]
}
}
]
} = response;
console.log(lat, lng);

您还可以将结果保存在变量/常量中,然后遍历到coordinates数组:

const response = await fetch('http://localhost/data.json', {method: 'GET'})
const result = await response.json()
const coordinates = result.location[0].geometry.coordinates

此外,您可能需要使用coordinates以以下方式获得latitudelongitude

const [latitude, longitude] = coordinates;
// or
const latitude = coordinates[0]
const loingitude = coordinates[1]

响应中的location数组可能包含几个具有不同coordinates对象,您将使用map函数对结果进行处理:

const locations = result.location // get the location array
const newArrayOfLocations = locations.map(location => (
{
center: [location.geometry.coordinates[0], location.geometry.coordinates[1]],
essential: true
})
)

您也可以在map函数中使用阵列销毁:

locations.map(location => {
const [latitude, longitude] = location.geometry.coordinates
return {
center: [latitude, longitude],
essential: true
}}
)

谢谢,但上面的答案都不起作用,我用以下代码完成了它:

const response = await fetch(

'http://localhost/data.json', {
method: 'GET'
})
const results = await response.json()
const longitude = results.locations[0].geometry.coordinates[0]
const latitude = results.locations[0].geometry.coordinates[1]