简体   繁体   English

如何过滤 JSON 文件以使用 Javascript 检索 HTML 数据

[英]How do I Filter a JSON file to retrieve data for HTML with Javascript

I have a JSON file that I'm trying to filter the data so it only returns data for a specific Institution and then insert that into HTML.我有一个 JSON 文件,我正在尝试过滤数据,因此它只返回特定机构的数据,然后将其插入到 HTML 中。

Here is the JSON file:这是 JSON 文件:

[
    {
    "Institution 1":
             {
                "institution" : "Fiscal targets and rules",
                "InstitutionalStrength":"Medium:  Limited legal debt constraints; no legal fiscal rules",
                "Effectiveness":"Medium: Conservative fiscal policy has resulted in limited deficits and improving debt sustainability"
             },

    "Institution 2":
            {
                "institution" : "National and sectoral planning",
                "InstitutionalStrength":"Medium:  Limited legal debt constraints; no legal fiscal rules",
                "Effectiveness":"Medium: Conservative fiscal policy has resulted in limited deficits and improving debt sustainability"
                
            },
            
    "Institution 3":
            {
                "institution" : "Coordination among entities",
                "InstitutionalStrength":"Medium:  Limited legal debt constraints; no legal fiscal rules",
                "Effectiveness":"Medium: Conservative fiscal policy has resulted in limited deficits and improving debt sustainability"
                
            }
}
]

Here is my HTML & JavaScript这是我的 HTML 和 JavaScript

<div style="padding:0 0 0 20;">

   

    <p>INSTITUTION<br>

    <span class="w3-large"><b>1. Fiscal Targets and Rules</b></span></p>

    <br><b>SUMMARY ASSESMENT</b><br><br>

  <div id="myData"></div>
  </div>


<script>
        fetch('institutionalstrength.json')
            .then(function (response) {
                return response.json();
            })
            .then(function (data) {
                appendData(data).filter(function(x){ return x.institution == "Fiscal targets and rules"; });
            })
            .catch(function (err) {
                console.log('error: ' + err);
            });
        function appendData(data) {
            var mainContainer = document.getElementById("myData");
            for (var i = 0; i < data.length; i++) {
                var div = document.createElement("div");
                div.innerHTML = '<bold>Institutional Design:</bold> ' + data[i].InstitutionalStrength + ' <br>Effeciveness: ' + data[i].Effectiveness;
                mainContainer.appendChild(div);
            }
        }
    </script>

I feel like I'm close.我觉得我很接近。 I can manipulate the JSON a little before it gets to me but this is a file that I don't have much control over.我可以在 JSON 到达我面前稍微操作一下,但这是一个我没有太多控制权的文件。

Thanks.谢谢。

There are several problems :有几个问题:

  • Your filter call is not at the good place.您的filter调用不在合适的位置。
  • The way your JSON is formatted make it not so easy to achieve what you want to do JSON 的格式化方式使实现您想要做的事情变得不那么容易

If you can change your JSON like this :如果您可以像这样更改 JSON:

[
  {
    "institution" : "Fiscal targets and rules",
    "InstitutionalStrength":"Medium:  Limited legal debt constraints; no legal fiscal rules",
    "Effectiveness":"Medium: Conservative fiscal policy has resulted in limited deficits and improving debt sustainability"
  },
  {
    "institution" : "National and sectoral planning",
    "InstitutionalStrength":"Medium:  Limited legal debt constraints; no legal fiscal rules",
    "Effectiveness":"Medium: Conservative fiscal policy has resulted in limited deficits and improving debt sustainability"
  },
  {
    "institution" : "Coordination among entities",
    "InstitutionalStrength":"Medium:  Limited legal debt constraints; no legal fiscal rules",
    "Effectiveness":"Medium: Conservative fiscal policy has resulted in limited deficits and improving debt sustainability"
  }
]

Then a code like this could do the job :然后像这样的代码可以完成这项工作:

function appendData(data) {
  const mainContainer = document.getElementById("myData");
  for (let institution in data) {
    const div = document.createElement("div");
    div.innerHTML = 'Institutional Design : ' + data[institution].InstitutionalStrength + ' <br>Effeciveness: ' + data[institution].Effectiveness;
    mainContainer.appendChild(div);
  };
}

fetch('institutionalstrength.json')
  .then(response => response.json())
  .then(json => appendData(json.filter(jsonItem => jsonItem.institution === 'Fiscal targets and rules')))
  .catch(err => console.log(`error : ${err}`));
  • Last but not least, there is a lot of very old school code here, try to avoid innerHTML, tags like <bold> , == (use === instead if possible, + concatenations and var declarations.最后但并非最不重要的一点是,这里有很多非常古老的代码,尽量避免使用innerHTML,像<bold>==这样的标签(如果可能,请使用 === 代替, +连接和var声明。

Since appendData doesn't return anything, you probably want appendData(data.filter instead of appendData(data).filter :由于 appendData 不返回任何内容,您可能需要appendData(data.filter而不是appendData(data).filter

        fetch('institutionalstrength.json')
            .then(function (response) {
                return response.json();
            })
            .then(function (data) {
                appendData(data.filter(function(x){ return x.institution == "Fiscal targets and rules"; }));
            })
            .catch(function (err) {
                console.log('error: ' + err);
            });
        function appendData(data) {
            var mainContainer = document.getElementById("myData");
            for (var i = 0; i < data.length; i++) {
                var div = document.createElement("div");
                div.innerHTML = '<bold>Institutional Design:</bold> ' + data[i].InstitutionalStrength + ' <br>Effeciveness: ' + data[i].Effectiveness;
                mainContainer.appendChild(div);
            }
        }

Additionally, you can use arrow functions to make the code easier to understand :此外,您可以使用箭头函数使代码更易于理解:

appendData(data.filter(x => x.institution == "Fiscal targets and rules"));

暂无
暂无

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

相关问题 如何通过HTML表单输入文本并使用Javascript从JSON文件中检索数据作为响应? - How do I input text via an HTML form and retrieve data from a JSON file as a response using Javascript? 如何从JavaScript变量检索JSON数据 - How do I retrieve json data from a javascript variable 如何将 JSON 文件数据显示到 HTML 表中(仅使用 JavaScript,而不是 jQuery) - How do I display JSON file data into HTML table (using JavaScript only, not jQuery) 如何使用 JavaScript 将 HTML 表单的输入保存到 JSON 文件中? - How do I save the inputs of an HTML form into a JSON file with JavaScript? 如何存储JSON文件的内容,以便可以检索多个JSON对象及其数据 - How do I store the contents of a JSON file so that I can retrieve multiple JSON objects and their data 我如何过滤json获取数据 - how do i filter json get data 如何使用JavaScript更新保存在JSON文件中的数据? - How do I update the data saved in a JSON file using JavaScript? 如何检索列在其中的JSON编码数组 <div> 从JavaScript文件? - How do I retrieve a JSON encoded array printed inside a <div> from a JavaScript file? 如何使用JavaScript从html5 canvas检索原始位图数据? - How do I retrieve raw bitmap data from html5 canvas using JavaScript? 如何在此 HTML 页面中存储数据并使用 JavaScript 在另一个页面中检索它 - How do I store data in this HTML page and retrieve it in another using JavaScript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM