Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
358 views
in Technique[技术] by (71.8m points)

javascript - 如何在JavaScript中读取外部本地JSON文件?(How to read an external local JSON file in JavaScript?)

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.

(我已在本地系统中保存了一个JSON文件并创建了一个JavaScript文件,以便读取JSON文件并打印出数据。)

Here is the JSON file:

(这是JSON文件:)

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

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

(假设这是JSON文件的路径: /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 inside it in JavaScript?

(有谁能帮我写一段简单的代码来读取JSON文件并用JavaScript打印其中的数据?)

  ask by user2864315 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

(要使用javascript读取外部Local JSON文件(data.json),首先要创建data.json文件:)

data = '[{"name" : "Ashwin", "age" : "20"},{"name" : "Abhinandan", "age" : "20"}]';
  1. Mention the path of the json file in the script source along with the javascript file.

    (提及脚本源中json文件的路径以及javascript文件。)

     <script type="text/javascript" src="data.json"></script> <script type="text/javascript" src="javascrip.js"></script> 
  2. Get the Object from the json file

    (从json文件中获取Object)

     var mydata = JSON.parse(data); alert(mydata[0].name); alert(mydata[0].age); alert(mydata[1].name); alert(mydata[1].age); 

For more information, see this reference .

(有关更多信息,请参阅此参考 。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...