简体   繁体   中英

JavaScript - JSON loading by dynamical value

I want to load the following JSON-structure seen in this function.

       function load1(input) {
            var txt = '{ "kind1" : [{ "name":"blue" , "color":"blue" },{ "name":"red" , "color":"red" },{ "name":"yellow" , "color":"yellow" } ], "kind2" : [{ "name":"blue2" , "color":"blue2" },{ "name":"red2" , "color":"red2" },{ "name":"yellow2" , "color":"yellow2" } ]}';
            var obj = eval("(" + txt + ")");
            var output = "";

            for (var i in obj.kind1) {
                output += obj.kind1[i].name + ", " + obj.kind1[i].color + "<br>"
            }
            document.getElementById("content").innerHTML = output + "Eingabe: " + input
        }

Now I need the function loading JSON dynamically by the "id" of the link.

<a onclick="return load1(this.id)" id="kind1">link_product1</a>
<a onclick="return load2(this.id)" id="kind2">link_product2</a>

Is it possible to change the query "obj.kind1" to do this? I can load the id into function, but replacing "kind1" with "input" is not working. Anybody can show how this logic would work?

Since you have txt hard coded in your function body, it seems to me that you could just hard code the actual JavaScript objects you want to work with and skip the eval step. If there's some reason you don't want to do this, you should use JSON.parse instead. It is supported even by relatively old browsers (IE8).

Then, you can access the provided key with bracket notation:

for (var i = 0; i < obj[input].length; i++) {
    output += obj[input][i].name //etc.

EDIT: based on your "Im using function getJSON," this seems to say that you are using jQuery and $.parseJSON is available instead. The data returned to the getJSON callback does not need to be parsed . It should already be JavaScript constructs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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