How to read an external local JSON file in JavaScript

798    Asked by behail_3566 in Python , Asked on Jul 3, 2021

 I have saved a JSON file in my local system and created a JavaScript file in order to read the JSON file and print data out. Here is the JSON file:

{"resource":"A","literals":["B","C","D"]}

Let’s say this is the path of the JSON file: /Users/Documents/workspace/test.json.

Could anyone please help me write a simple piece of code to read the JSON file and print the data in JavaScript? How javascript load json file?

Answered by bhagwati dubey

For reading the external Local JSON file (data.json) using javascript, first create your data.json file:

    data = '[{"name" : "Niroj", "age" : "22"},{"name" : "Dey", "age" : "20"}]';

Mention the path of the json file in the script source along with the javascript file.



Get the Object from the json file
var mydata = JSON.parse(data);
alert(mydata[0].name);
alert(mydata[0].age);
alert(mydata[1].name);
alert(mydata[1].age);
Hope it helps!!

Your Answer

Interviews

Parent Categories