xxxxxxxxxx
Using fetch function
Code to access employees.json using fetch function −
fetch("./employees.json")
.then(response => {
return response.json();
})
.then(data => console.log(data));
xxxxxxxxxx
fetch("file.json")
.then(Response => Response.json())
.then(data => {
console.log(data);
// or whatever you wanna do with the data
});
xxxxxxxxxx
<script type="module">
import data from "./data.json" assert { type: "json" };
console.log(data);
</script>
// also add this=> type:"module" in json file as object
xxxxxxxxxx
const fs = require('fs');
fs.readFile('./customer.json', 'utf8', (err, jsonString) => {
if (err) {
console.log("File read failed:", err)
return
}
console.log('File data:', jsonString)
})
xxxxxxxxxx
import countryTable from "./data/countries.json" assert { type: "json" };
xxxxxxxxxx
Using fetch function
Code to access employees.json using fetch function −
fetch("./employees.json")
.then(response => {
return response.json();
})
.then(data => console.log(data));
xxxxxxxxxx
// using Promise
fetch("my.json")
.then(response => response.json())
.then(parsed => /* parsed contains the parsed json object */);
// or if you can use async/await
let response = await fetch("my.json");
let parsed = await response.json();
xxxxxxxxxx
// read remote JSON file in javascript
fetch("https://jsonplaceholder.typicode.com/users")
.then(function (response) {
return response.json();
})
.then(function (data) {
for (let i = 0; i < data.length; i++) {
console.log(data[i]);
}
})
xxxxxxxxxx
// using Promise
fetch("my.json")
.then(response => response.json())
.then(parsed => /* parsed contains the parsed json object */);
// or if you can use async/await
let response = await fetch("my.json");
let parsed = await response.json();
xxxxxxxxxx
<script type="text/javascript" src="data.json"></script>
<script type="text/javascript" src="javascrip.js"></script>