使用变量作为JSON上的键

时间:2016-04-09 03:25:48

标签: javascript jquery arrays json

我的json是这样的: `

{
    "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%"

    }
]
      }

并获得JSON对象我将使用这样的:

                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 

如果您看到我使用data.isfahan获取数组,一切正常,但如果我将data.isfahan更改为`data.pulse_state&#39; ,它出错!!!!!

我的意思是我想使用名为data.pulse_state的变量,然后获取JSON对象,

你可以帮帮我吗?

1 个答案:

答案 0 :(得分:2)

尝试

data[pulse_state]

而不是data.pulse_state