+ 1

How to use an external json file

I have a JSON file on GitHub or in the cloud. How can I download and use it in my JS script?

3rd Mar 2020, 8:33 PM
Š’Š»Š°Š“ ŠŠ½Ń‚ŠµŠµŠ²
Š’Š»Š°Š“ ŠŠ½Ń‚ŠµŠµŠ² - avatar
3 Answers
+ 1
fetch(jsonFile) .then(response => response.json()) .then(json => JSON.stringify(json, null, 2)) .then(text => console.log(text)); https://code.sololearn.com/WEwT85uu3Y3q/?ref=app https://code.sololearn.com/WMRV3ZREEniR/?ref=app
4th Mar 2020, 1:25 AM
CalviÕ²
CalviÕ² - avatar
+ 1
how to access JSON file in js =>you can access the JSON file data with help of JSON.parse method =>function loadJSON(callback) { var xobj = new XMLHttpRequest(); xobj.overrideMimeType("application/json"); xobj.open('GET', 'my_data.json', true); xobj.onreadystatechange = function () { if (xobj.readyState == 4 && xobj.status == "200") { callback(xobj.responseText); } }; xobj.send(null); } => Get the Object from the JSON file function init() { loadJSON(function(response) { // Parse JSON string into object var actual_JSON = JSON.parse(response); }); } (2) data = '[{"name" : "Ashwin", "age" : "20"},{"name" : "Abhinandan", "age" : "20"}]'; script type="text/javascript" src="data.json"></script> <script type="text/javascript" src="javascrip.js"></script> var mydata = JSON.parse(data); alert(mydata[0].name); alert(mydata[0].age); alert(mydata[1].name); alert(mydata[1].age);
4th Mar 2020, 4:38 AM
Ishan Shah
Ishan Shah - avatar
0
Thank you all
4th Mar 2020, 6:05 AM
Š’Š»Š°Š“ ŠŠ½Ń‚ŠµŠµŠ²
Š’Š»Š°Š“ ŠŠ½Ń‚ŠµŠµŠ² - avatar