访问JSON键/数组值的多个实例到HTML

时间:2019-04-29 14:19:30

标签: javascript jquery json

我的第一个/实例输出正常。但是,如果从'ZipSearch'变量(这是JSON标头,即下面的JSON代码中,值为23222)发现多个, "23222":[ ...

下面是最近使用[2]的尝试,也尝试过[1]等。关于如何输出具有公共Key值的以下JSON数据的内容的任何想法吗?进入我的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"}
],

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

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

    <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"]);
                })

1 个答案:

答案 0 :(得分:1)

如果您的对象是

 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"]);
    })