如何解析JSON文件并查找特定键然后返回值?

时间:2013-11-20 21:13:33

标签: jquery json getjson

JSON新手在这里。我试图从JSON文件中查找特定值。基本上,我有一个搜索框,用户可以从自动完成下拉列表中的现有“名称”列表中选择“名称”(请参阅​​jSON)。我们的想法是返回输入的“名称”的相应“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" />

1 个答案:

答案 0 :(得分: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