根据接收到的输入从JSON中获取数据

Get data from JSON based upon the input received

本文关键字:JSON 获取 数据 输入      更新时间:2023-09-26

我需要根据收到的输入获取数据。

例如,如果输入是"Royal python",我应该得到Royal python的详细信息。但使用以下代码,我会得到一个错误,说"你要求的文件不存在"。但我把值输入了fname。但不确定该函数从数组中提取数据是否正确。我也想知道是否有更短的方法可以做到这一点。请帮忙?

我使用JavaScript,我的代码和网页外观如下:

<!DOCTYPE html> 
<html> 
<body>  
<form> <input type="text" name="fname" required> 
<button onclick="myFunction()">OK</button> `enter code here`
</form>  
<p id="demo"></p>  
<script> var text = '{"animals":[' + 
'{"Common Name":"Royal Python","Order":"Squamata","Family":"Boidae","Genus":"Python","Species":"regius","Zoo":"Blackpool Zoo","Number":4 },' + 
'{"Common Name":"Emperor Penguin","Order":"Sphenisciformes","Family":"Spheniscidae","Genus":"Aptenodytes","Species":"forsteri",`   "Zoo":"Welsh Mountain Zoo","Number":35 },' +` 
'{"Common Name":"Chimpanzee","Order":"Primates","Family":"Pongidae","Genus":"Pan","Species":"troglodytes",    "Zoo":"Blackpool Zoo","Number":8 }]}';  
obj = JSON.parse(text);  

//function to fetch data based on input
function myFunction(fname) 
{ var ani = ""; 
if (document.getElementByname("fname")="Royal Python")   
var ani =  document.getElementById("demo").innerHTML = obj.animals[0].Zoo + " " + obj.animals[0].Species; }}  </body> </html>

这里有一个问题的解决方案,它使用for循环来检查动物数组的每个索引是否匹配。此匹配也将不区分大小写。

<!DOCTYPE html>
<html>
<body>
    <p id="demo"></p>
    <input type="text" name="fname" required>
    <button onclick="fetchAnimal()">OK</button> `enter code here`
    <script>
    var animalsArr = [{
        "commonName": "Royal Python",
        "order": "Squamata",
        "family": "Boidae",
        "genus": "Python",
        "species": "regius",
        "zoo": "Blackpool Zoo",
        "number": 4
    }, {
        "commonName": "Emperor Penguin",
        "order": "Sphenisciformes",
        "family": "Spheniscidae",
        "genus": "Aptenodytes",
        "species": "forsteri",
        "zoo": "Welsh Mountain Zoo",
        "number": 35
    }, {
        "commonName": "Chimpanzee",
        "order": "Primates",
        "family": "Pongidae",
        "genus": "Pan",
        "species": "troglodytes",
        "zoo": "Blackpool Zoo",
        "number": 8
    }]
    function fetchAnimal() {
        var i;
        var len = animalsArr.length;
      
        // convert input name to lower-case
        var name = document.getElementsByName('fname')[0].value.toLowerCase();
        for (i = 0; i < len; i++) {
            // check to see if lower-case input is the same as lower-case animal name (this ensures the match is case-insensitive)
            if (animalsArr[i].commonName.toLowerCase() === name) {
                document.getElementById('demo').innerHTML = animalsArr[i].zoo + ' ' + animalsArr[i].species;
            }
        }
    }
    </script>
</body>
</html>

注意:如果您想为页面添加更多的交互性,强烈建议将JS代码移动到外部脚本文件中。

您的代码中存在许多问题:

document.getElementByname("fname")="Royal Python"应为document.getElementsByName("fname")[0].value == "Royal Python"

此外,编写文本字符串然后将其解析为JSON也很麻烦。只需使用一个JavaScript对象。

当你试图确定动物时,你也会给自己带来困难。如果您的浏览器支持Array.findIndex(),请使用它。

下面是一个工作示例:

var obj = {animals:[{CommonName:"Royal Python",Order:"Squamata",Family:"Boidae",Genus:"Python",Species:"regius",Zoo:"Blackpool Zoo",Number:4 }, {CommonName:"Emperor Penguin",Order:"Sphenisciformes",Family:"Spheniscidae",Genus:"Aptenodytes",Species:"forsteri",Zoo:"Welsh Mountain Zoo",Number:35 }, {CommonName:"Chimpanzee",Order:"Primates",Family:"Pongidae",Genus:"Pan",Species:"troglodytes",    Zoo:"Blackpool Zoo",Number:8 }]};
//function to fetch data based on input
function myFunction() { 
  var name = document.getElementsByName("fname")[0].value;
  var index = obj.animals.findIndex(function(item) {
    return item.CommonName === name;
  });
  if (index >= 0) {
    document.getElementById("demo").innerHTML = obj.animals[index].Zoo + " " + obj.animals[index].Species;
  }
}
<input type="text" name="fname" required value="Royal Python"> 
<button onclick="myFunction()">OK</button>
<p id="demo"></p>