I'm new to coding and have trouble with this nested JSON file.
I want to display the EV-charging stations in Switzerland on a webpage built with HTML, CSS, and JavaScript. For the data, I have an external JSON file that I want to access with JavaScript.
This is the external JSON file "ladestationen_schweiz.json" and I want to access the Google GeoCoordinates "46.68459 7.86187" with JavaScript.
{
"EVSEDataRecord":[
{
"Address":{
"City":"Interlaken",
"Country":"CHE",
"HouseNum":"16",
"PostalCode":"3800",
"Street":"Alpenstrasse",
"Floor":null,
"Region":null,
"Timezone":null
},
"IsOpen24Hours":false,
"ChargingStationId":"CH*BVS*E001*0001",
"GeoCoordinates":{
"Google":"46.68459 7.86187"
}
}
]
}
Could somebody help me?
Here is a picture of the overview of my project
CodePudding user response:
Yes, the json you are getting is an array EVSEDataRecord so you need to map this to get the single object and then any field inside object you can access.
Below in code i did the same thing or click here for demo
import React from 'react';
import MyData from './ladestationen_schweiz.json';
export default function App() {
return (
<div>
<h1>JSON!</h1>
{MyData.EVSEDataRecord.map((item) => {
return <div>Google: {item.GeoCoordinates.Google}</div>;
})}
</div>
);
}
CodePudding user response:
Assuming you are not using a preprocessor like Babel, you will need to fetch the json using fetch api because the current ES implementation does not support widely direct json imports.
An example of import using fetch:
fetch("./path/to/your/data.json")
.then((r) => r.json())
.then((obj) => console.log(obj));
Variable obj will then hold contents of your json file.
CodePudding user response:
Using Square brackets property accessor, Dot property accessor and Object/Array destructuring
const jsonData = {
"EVSEDataRecord": [{
"Address": {
"City": "Interlaken",
"Country": "CHE",
"HouseNum": "16",
"PostalCode": "3800",
"Street": "Alpenstrasse",
"Floor": null,
"Region": null,
"Timezone": null
},
"IsOpen24Hours": !1,
"ChargingStationId": "CH*BVS*E001*0001",
"GeoCoordinates": {
"Google": "46.68459 7.86187"
}
}]
}
// Using Square brackets property accessor
console.log(jsonData['EVSEDataRecord'][0]['GeoCoordinates']['Google']);
// Using Dot property accessor
console.log(jsonData.EVSEDataRecord[0].GeoCoordinates.Google);
// using Object destructuring
const {
EVSEDataRecord: [{
GeoCoordinates: {
Google
}
}]
} = jsonData;
console.log(Google);