开发者

Iterate through JSON object

I have a json object defined like this -

   "Content" : [ "Value1",
                 "Value2",
                 {"key": "value"},
                 {"key": "value"} 

               ] 

I can get the length of contents since it is an array.

How do I iterate through the object, so that I can display in this format-

    <div>Value1&开发者_运维知识库lt;/div>
    <div>Value2</div>
    <div><a href=key>Value</a></div>
    <div><a href=key>Value</a></div>

I am working on Javascript.

Thanks a lot!


If you had the variable

var c = {"Content" :["Value1","Value2",{"href": "key","val":"value"},{"href":"key","val":"value"}]}

you could then do what you wanted by using a for loop like this

   for(x in c.Content){
    if(typeof(c.Content[x])== "object"){
        var d = document.createElement("div");
        d.innerHTML = "<a href='"+c.Content[x].href+"'>"+c.Content[x].val+"</a>";
        document.body.appendChild(d);
    }else{
        var d = document.createElement("div");
        d.innerHTML = c.Content[x];
        document.body.appendChild(d);
    }
}

As you can see I did have to change your JSON slightly to make it easier on you to extract the information you want.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜