【问题标题】:Accessing multiple JSON files in JavaScript在 JavaScript 中访问多个 JSON 文件
【发布时间】:2013-08-16 01:10:08
【问题描述】:

我有一些精灵表,其中 atlus 以 JSON 格式保存。我正在根据structure from BrowserQuest 构建我的atlus。他们的每个 JSON 文件如下所示:

{
    "id": "agent",
    "width": 24,
    "height": 24,
    "animations": {
        "idle_down": {
            "length": 2,
            "row": 0
        }
    },
    "offset_x": -4,
    "offset_y": -8
}

但我想知道,如果它只是一个原始对象文字,我什至如何访问每个 JSON 文件中的数据?

由于每个 JSON 文件都是一个对象字面量,我能想象访问它的唯一方法是将对象字面量保存到一个变量中,例如

var agent = {
    "id": "agent",
    "width": 24,
    "height": 24,
    "animations": {
        "idle_down": {
            "length": 2,
            "row": 0
        }
    },
    "offset_x": -4,
    "offset_y": -8
};

我希望有一种访问 JSON 文件的简单方法。

因为每个单独的精灵表都有自己的 JSON 文件,所以我要加载大量文件。

加载如此大量的 JSON 文件的最佳方法是什么?我试图避免使用任何 JS 库。

【问题讨论】:

  • 尽量避免使用 JQuery 和任何 JS 库
  • 然后自己实现XHR请求和JSON.parse响应。然而 - 坦率地说 - 当所有的工作和数百个其他事情都已经由 jQuery 完成时,这是相当愚蠢的。
  • 您可能会在 MDN 中看到信息:developer.mozilla.org/en-US/docs/JSON 据我了解,许多现代浏览器都内置了 JSON 解析器。另见docs.webplatform.org/wiki/apis/json
  • 您还可以使用构建过程为您组合(和缩小)文件。这样,您可以将它们分开进行编辑,但在准备好运行/测试代码时将它们组合成一个块。要开始使用,旧的 copy 命令将起作用。 copy file1+file2+file3 bigfile.js

标签: javascript json


【解决方案1】:

首先,回答您的问题:

但我想知道,如果它只是一个原始对象文字,我什至如何访问每个 JSON 文件中的数据?

JSON 代表 JavaScript Object Notation,因此与如果它是一个 JavaScript 对象,它将被操纵。

至于访问JSON文件,如果它是本地文件,你可以这样:

function doStuff(json){
    console.log(json);
}

var oReq = new XMLHttpRequest();
oReq.addEventListener("load", function(){
    doStuff(JSON.parse(this.responseText));
});
oReq.open("GET", "http://www.example.com/example.json");
oReq.send();

然后您可以将doStuff 替换为处理 JSON 的任何函数。

【讨论】:

  • 你在做什么?您编辑一个旧问题,发布赏金,然后自己回答问题。您是否正在想办法获得帽子?
  • 尝试回答->编辑->赏金之类的,清理过程中的旧问题没有害处
  • 没什么害处...这让我觉得很奇怪。
  • 我在这里闻到了一股腥味。虽然我不能说什么。
  • Supersharp,使用 eventListeners 比使用 onload 更好,因为您可以附加无限数量的事件侦听器,而只有一个 onload,并且您不能将函数引用传递给 onload。
【解决方案2】:

您可以使用XMLHttpObject

看看

function getJSONFile(url,callback) {   
  var req = new XMLHttpRequest();
  req.open('GET', url, true); 
  req.overrideMimeType("application/json");
  req.onreadystatechange = function () {
      if (req.readyState == 4 && req.status == "200") {
        callback(req.responseText);
      }
  };
req.send();  
}

像这样使用这个函数

getJSONFile('http://www.example.com/example.json', function(data){
  if(data)
    console.log('json data : ' + JSON.stringify(data));
})

【讨论】:

    【解决方案3】:

    您可以通过结合使用 PromiseXMLHttpRequest 来并行加载多个 JSON 文件。

    这个有趣的article from HTML5Rocks 应该对您的下载控制和优化也有很大帮助,因为它全面而实用。

    例如,使用get(url) 函数(来自上面的文章,参见下面的源代码)将 JSON 对象作为Promise 返回:

    var names = [ "agent", "arrow", ... ]
    var sprites = {}
    
    var all = []
    names.forEach( function ( n ) {
      //Request each individual sprite and get a Promise
      var p = get( n + ".json" )
                  .then( JSON.parse ) //parse the JSON file
                  .then ( function ( sprite ) {
                     //Record the sprite by name
                     sprites[n] = sprite 
                     //Display your sprite as soon as loaded here     
                  } )
      //add the promise to an Array of all promises
      all.push( p )
    } )
    
    //wait for all the files to be loaded and parsed
    Promise.all( all )
        .then( function () {
            //All the  JS sprites are loaded here
            //You can continue your processing
        } )
    

    get(url) 的来源:

    这是来自 HTML5Rocks 的示例代码。它在Promise 中封装了一个 XMLHttpRequest 异步调用:

    function get(url) {
      return new Promise(function(resolve, reject) {
        var req = new XMLHttpRequest()
        req.open( 'GET', url )
        req.onload = function() {
          if ( req.status == 200 ) 
            // Resolve the promise with the response text
            resolve(req.response)
          else
            // Otherwise reject with the status text
            reject( Error( req.statusText ) )
        }
    
        // Handle network errors
        req.onerror = function() {
          reject( Error( "Network Error" ) )
        }
    
        // Make the request
        req.send()
      } )
    }
    

    【讨论】:

    • 如果你能包含一个代码示例来展示 Promise 的使用,那就太好了。
    猜你喜欢
    • 1970-01-01
    • 2019-03-26
    • 2020-04-11
    • 2018-07-18
    • 1970-01-01
    • 2019-03-31
    • 2016-06-18
    • 2015-03-11
    • 2012-05-21
    相关资源
    最近更新 更多