Javascript 将本地 JSON 文件读入变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48073151/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:01:23  来源:igfitidea点击:

read local JSON file into variable

javascriptjson

提问by Joshua Terrill

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, for instance. Here is the JSON file:

例如,我在本地系统中保存了一个 JSON 文件并创建了一个 Javascript 文件,以便读取 JSON 文件并打印数据。这是 JSON 文件:

[
{"Titel":"a", 
    "Timestamp":"2017-05-18 22:11",
    "Text":"a", 
    "img":"a.jpg",
    "FullText":"a"
},
{"Titel":"b",
    "Timestamp":"2017-08-08 22:11",
    "Text":"b",
    "img":"b.jpg",
    "FullText":"b" }]

Lets say this is the path where it takes you to the JSON file:

假设这是将您带到 JSON 文件的路径:

../news_data.json

Could anyone please help me with writing a simple piece of codes to read the JSON file and print the data inside it in Javascript. I am very new to Javascript and need something simple to start with. Your assistance would be very much appreciated.

任何人都可以帮我写一段简单的代码来读取 JSON 文件并用 Javascript 打印其中的数据。我对 Javascript 很陌生,需要一些简单的东西来开始。非常感谢您的帮助。

回答by Joshua Terrill

Here's a way to do it without jQuery.

这是一种无需 jQuery 即可完成的方法。

First create this function:

首先创建这个函数:

function loadJSON(callback) {   
  var xobj = new XMLHttpRequest();
  xobj.overrideMimeType("application/json");
  xobj.open('GET', '../news_data.json', true);
  xobj.onreadystatechange = function () {
    if (xobj.readyState == 4 && xobj.status == "200") {
      callback(JSON.parse(xobj.responseText));
    }
  };
  xobj.send(null);  
}

Then you can use it by simply calling something like this:

然后你可以通过简单地调用这样的东西来使用它:

loadJSON(function(json) {
  console.log(json); // this will log out the json object
});

I found this by simply googling "read local json file javascript" (source)

我通过简单地谷歌搜索“读取本地 json 文件 javascript”(源代码)发现了这一点

回答by Aman Kumar

You can use jQuery.getJSON()in jquery

你可以在 jquery 中使用jQuery.getJSON()

First add jquery CDN :

首先添加 jquery CDN :

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

Now set full json file path as ex :- folder/file.json

现在将完整的 json 文件路径设置为 ex :- folder/file.json

Description:Load JSON-encoded data from the server using a GET HTTP request.

描述:使用 GET HTTP 请求从服务器加载 JSON 编码的数据。

$.getJSON( "JSON FILE PATH", function( data ) {

    console.log(data); //json output 
});

DEMO

演示

(function() {
  var flickerAPI = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
  $.getJSON( flickerAPI, {
    tags: "mount rainier",
    tagmode: "any",
    format: "json"
  })
    .done(function( data ) {
      $.each( data.items, function( i, item ) {
        $( "<img>" ).attr( "src", item.media.m ).appendTo( "#images" );
        if ( i === 3 ) {
          return false;
        }
      });
    });
})();
 img {
    height: 100px;
    float: left;
  }
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>jQuery.getJSON demo</title>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
 
<div id="images"></div>

</body>
</html>