如何从JSONObject获取vlaue?

时间:2016-01-22 14:27:47

标签: javascript json for-loop coldfusion

我有带日期值的JSONObject。每个日期或日期范围都有ID。我用这段代码创建了JSON:

<script>
    <cfset dateStruct = structNew() />
    <cfoutput query="qryOne">
        <cfset dateStruct[userID] = arrayNew(1) />
        <cfloop from="#PickDateTime#" to="#DropDateTime#" index="i" step="#CreateTimeSpan(1,0,0,0)#">
            <cfset arrayAppend(dateStruct[userID],"#dateformat(i,'mmddyyyy')#")/>
        </cfloop>
    </cfoutput>

    var jsonString =  '<cfoutput>#SerializeJSON(dateStruct)#</cfoutput>';
    var JSONObject = JSON.parse(jsonString);

    function giveClass(){
        for(var key in JSONObject){
            res = document.getElementById(JSONObject[key]);
            res.className = 'booked'
        }
    }
</script>

我在jsonString上发出了警告,看起来像这样:

{"49":["01082016","01092016"],"48":["03012016","03022016","03032016","03042016","03052016","03062016","03072016","03082016","03092016","03102016","03112016","03122016","03132016","03142016","03152016","03162016","03172016","03182016","03192016","03202016","03212016","03222016","03232016","03242016","03252016","03262016","03272016","03282016","03292016","03302016","03312016"],"44":["01122016"],"47":["02062016"],"46":["02112016","02122016","02132016","02142016","02152016"],"35":["01132016"],"36":["01212016"],"39":["01162016"],"37":["01262016"],"38":["01192016"],"43":["01312016"],"42":["02022016","02032016"],"41":["01142016"],"40":["01172016","01182016","01192016"],"51":["01282016"],"52":["02252016","02262016"],"50":["01282016"]}

每个日期都存储在唯一ID下。在我上面的函数中,我想将className ='scheduled'分配给每个ID,我想分配给每个值。例如,如果我有id:"42":["02022016","02032016"],我想给两个值赋予类名,而不仅仅是id 42.我的函数现在只给我id的类,我怎么能让它为每个值给我一个类名?

1 个答案:

答案 0 :(得分:3)

您需要遍历每个数组:

function giveClass(){
    for(var key in JSONObject){     
        for(var i=0;i<JSONObject[key].length;++i){
            var res2 = document.getElementById(JSONObject[key][i]);   
            res2.className = 'booked';
        }            
    }
}

正如Pointy所说:

  

您可以将JSON直接放入JavaScript代码中。它没有   必须是一个字符串,你不必明确解析它;只是   将其创建为纯JavaScript。