【问题标题】:How to parse a JSON file and lookup for a specific key and then return value?如何解析 JSON 文件并查找特定键然后返回值?
【发布时间】:2013-11-20 21:13:33
【问题描述】:

这里是 JSON 新手。我正在尝试从 JSON 文件中查找特定值。基本上,我有一个搜索框,用户可以在其中从自动完成下拉列表中的现有“名称”列表中选择一个“名称”(参见 jSON)。思路是返回输入的“name”对应的“url”值。

JSON (docs.json):

[
    { "tag": "Tutorial", "name": "Using Cloud", "url": "http://example.com/staff/doc/platform_training/index.html" },
    { "tag": "Tutorial", "name": "Help Tutorials", "url": "http://example.com/mason/staff/doc/tutorials/help/agent.html" },
    { "tag": "Tutorial", "name": "Big Stuff", "url": "http://example.com/mason/staff/doc/tutorials/orientation.html" }

]

jQuery:

        $('.livesearch').keypress(function (e) {
        if (e.which == 13) {
        searchTerm = $("#search").val();
        // return the "url" based on the "searchTerm", which is basically the "name" key in the JSON file
        }

        });


        function readJSON(searchTerm) {
            $.getJSON( "json/docs.json", function( data ) {
                $.each( data, function( key, val ) {
                    // 
                });
            });

        }

HTML:

<input class="livesearch" type="text" placeholder="Enter your search terms here" id="search" />

【问题讨论】:

    标签: jquery json getjson


    【解决方案1】:

    设置searchTerm 后,调用readJSON(searchTerm) 函数,然后在回调中执行:

    var url = "";
    for (var i = 0; i < data.length; i++) {
        if (data[i].hasOwnProperty("name")) {
            if (data[i].name == searchTerm) {
                url = data[i].name;
                break; //bye bye for loop
            }
        }
    }
    
    //do stuff
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-04-25
      • 1970-01-01
      • 1970-01-01
      • 2016-10-23
      • 1970-01-01
      • 1970-01-01
      • 2015-04-29
      相关资源
      最近更新 更多