简体   繁体   中英

use a Variable as a key on JSON

my json is like this : `

{
    "isfahan": [

    {  
        "id"   : "1",
        "city" : "ahar",                
        "top"  : "35%",
        "left" : "54%"

    },
    {  
        "id"   : "2",
        "city" : "marand",              
        "top"  : "35%",
        "left" : "54%"

    },
    {  
        "id"   : "3",
        "city" : "miane",               
        "top"  : "35%",
        "left" : "54%"

    }

],

"azerbaijan": [

    {  
        "id"   : "3",
        "city" : "miane",               
        "top"  : "35%",
        "left" : "54%"

    },
    {  
        "id"   : "3",
        "city" : "miane",               
        "top"  : "35%",
        "left" : "54%"

    }
],

"ardabil": [

    {  
        "id"   : "3",
        "city" : "miane",               
        "top"  : "35%",
        "left" : "54%"

    },
    {  
        "id"   : "3",
        "city" : "miane",               
        "top"  : "35%",
        "left" : "54%"

    },
    {  
        "id"   : "3",
        "city" : "miane",               
        "top"  : "35%",
        "left" : "54%"

    },
    {  
        "id"   : "3",
        "city" : "miane",               
        "top"  : "35%",
        "left" : "54%"

    }
]
      }

and to get JSON object i'm going to use such a this :

                var pulse_state = $('#state_var').html();

                $.getJSON("data/pulse.json").done(function(data){

                        localStorage.setItem("data", JSON.stringify(data));
                        $.each(data.isfahan, function(index, value){

                            $(".cd-points-container").append(
                               "<li class='cd-single-point' style='top:"+value.top+"; left:"+value.left+";'><a class='cd-img-replace' href='#0'>اطلاعات بیشتر</a><div class='cd-more-info cd-left'><h2>"+ value.city + "</h2><p>"+ value.sepah_text +"</p><a href='#0' class='cd-close-info cd-img-replace'>Close</a></div></li><!-- .cd-single-point -->"

                            );

                        });
                        //end each function 

as you see if i use data.isfahan to get array , everything is ok but if i change data.isfahan to `data.pulse_state' , it goes wrong !!!!!

i mean i want to use a variable named data.pulse_state and then get JSON object,

could you help me out ?

Try

data[pulse_state]

instead of data.pulse_state .

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