首页 > 解决方案 > 将 JSON 键/数组值的多个实例访问到 HTML

问题描述

我的第一个/实例输出很好。但是,如果从“ ZipSearch”变量中找到多个(这是 JSON 标头,即在下面的 JSON 代码中,父23222值), "23222":[ ...

下面是最近尝试使用[2]也尝试过[1]等。关于如何输出以下 JSON 数据的内容与公共 Key 值的任何想法?进入我的 HTML 页面?

                    $('span.zip').html(myjson[ZipSearch][0].Zipcode);
                    $('span.state').html(myjson[ZipSearch][0]["Primary State"]);
                    $('span.city').html(myjson[ZipSearch][0].City);
                    $('span.countyS').html(myjson[ZipSearch][0]["County S"]);
                    $('span.county').html(myjson[ZipSearch][0].County);

                    $('span.zip1').html(myjson[ZipSearch][2].Zipcode);
                    $('span.state1').html(myjson[ZipSearch][2]["Primary State"]);
                    $('span.city1').html(myjson[ZipSearch][2].City);
                    $('span.countyS1').html(myjson[ZipSearch][2]["County S"]);
                    $('span.county1').html(myjson[ZipSearch][2].County);

这是我的JSON

"23222":[ # sometimes has multiple responses per, ie below
{"Zipcode":"23222","City":"","Primary State":"Virginia","County S":"555","County":"Sample City"},
{"Zipcode":"23222","City":"","Primary State":"Utah","County S":"444","County":"Sample Bigger City"}
],

基本上,我无法在我的HTMLUtah页面中输出上面的第二行等……只是总是重复第一行的内容。

这是标记:(如果有多个公共数组,我只是想处理内容)

    <li class="zip">Zip Code: <span class="zip"></span></li>
    <li class="state">Primary State:  <span class="state"></span></li>
    <li class="city">City:  <span class="city"></span></li>
    <li class="countySSA">County SSA:  <span class="countyS"></span></li>
    <li class="county">County:  <span class="county"></span></li>

    <li class="zip1">Zip Code: <span class="zip1"></span></li>
    <li class="state1">Primary State:  <span class="state1"></span></li>
    <li class="city1">City:  <span class="city1"></span></li>
    <li class="countySSA1">County SSA:  <span class="countyS1"></span></li>
    <li class="county1">County:  <span class="county1"></span></li>

更新:

所以,我刚刚尝试了这个,在每个答案下面 - 它仍然只是将一组数组值打印到 HTML。

                myjson[ZipSearch].forEach(function(innerobj,index){
                    $('span.zip'+index).html(innerobj["Zipcode"]);
                    $('span.county'+index).html(innerobj["County"]);
                    $('span.county1'+index).html(innerobj["County"]);
                })

标签: javascriptjqueryjson

解决方案


如果你的对象是

 var obj=[ 
    {"Zipcode":"23222","City":"","Primary State":"Virginia","County S":"555","County":"Sample City"},
    {"Zipcode":"23222","City":"","Primary State":"Utah","County S":"444","County":"Sample Bigger City"}
    ]

用于每个访问多个对象

obj.forEach(function(innerobj,index){
        $('span.zip'+index).html(innerobj["Zipcode"]);
    })

推荐阅读