简体   繁体   English

比较动态JSON文件-JavaScript

[英]Compare dynamic JSON files - JavaScript

I've read the various questions regarding JSON object comparison, and am relatively confident that I can implement a comparison. 我已经阅读了有关JSON对象比较的各种问题,并且相对有信心可以实现比较。 My query is regarding loading of source .json files dynamically into JSON objects for comparison. 我的查询是关于将源.json文件动态加载到JSON对象中进行比较。

My scope for this project has been amended, such that a dynamically loaded .json file is checked for changes at a given interval. 我对该项目的范围进行了修改,以便在给定的时间间隔内检查动态加载的.json文件的更改。 The previous version of the application didn't require this, so the dynamic .json file was only loaded once. 该应用程序的先前版本不需要此功能,因此动态.json文件仅加载一次。 Below is the current implementation (single .json file only). 以下是当前的实现(仅单个.json文件)。

The jsdata.json file: jsdata.json文件:

var jsArray = [
    {
        "Value1": "Hello!",
        "Value2": "Second!"
    },
    {
        "Value3": "Third!",
        "Value4": "Last!"
    }
]

The HTML file: HTML文件:

var jsScript = document.createElement('script');
jsScript.setAttribute('id', 'jsFile');
jsScript.setAttribute('src', 'jsdata.json');
document.head.appendChild(jsScript);

//psJSON is called, passing the x variable

function psJSON(x) {
    $(document).ready(function(e) {
        if (jsArray[x].Value1 == "Hello!") {
            alert("Hello!");
        } else {
            alert("Sorry!");
        }
    )};
}

This current code works fine for retrieving data from the jsdata.json file. 此当前代码可用于从jsdata.json文件检索数据。 However, if I were to add a second .json file, I wouldn't know how to address the two files individually. 但是,如果要添加第二个.json文件,我将不知道如何分别处理这两个文件。

Is the $(document).ready() function the best approach to this, or is there a better way? 是$(document).ready()函数是实现此目的的最佳方法,还是有更好的方法?

First of all don't put variables in .json files. 首先,不要将变量放在.json文件中。

You can make this work by using $.getJSON() . 您可以使用$.getJSON()来完成这项工作。 This will return a promise. 这将返回一个承诺。 Do this once for every json file you have. 对您拥有的每个json文件执行一次。 Afterwards use $.when() to for wait for all of them to be resolved. 然后,使用$.when()等待所有问题被解决。

Working example: http://plnkr.co/edit/dFVbzzqRaZ03gfN9GWEo 工作示例: http//plnkr.co/edit/dFVbzzqRaZ03gfN9GWEo

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM