如何使用 jQuery 显示带有数组的 JSON 对象

How to display JSON object with an array using jQuery

本文关键字:数组 JSON 对象 何使用 jQuery 显示      更新时间:2023-09-26

我正在使用jQuery来解析和显示JSON文件中的数据。我得到了所有东西都可以在浏览器中吐出来,但我的 JSON 文件中的一个键有一个值数组。例如,这是我的 JSON:

{
  "category" : "Stuff",
  "location_id" : {
    "longitude" : "-71.89237903999964",
    "latitude" : "41.6809076720005",
    "human_address" : "{'"address'":'"156 Plainfield Pike Rd'",'"city'":'"Plainfield'",'"state'":'"CT'",'"zip'":'"06374'"}"
  },
}

这是我的jQuery代码:

$.getJSON('data.json', function(data) {
        var output = '<ul class="searchresults">';
        $.each(data, function(key, val) {
            if (val.item.search(myExp) != -1) {
                output += '<li>';
                output += '<p>' + "Category: " + val.category + '</p>';
                output += '<p>' + "Location: " + val.location_id + '</p>';
                output += '<p>' + "Business: " + val.business + '</p>';
                output += '</li>';
            }
        });
        output += '</ul>';
        $('#update').html(output);

出于某种原因,location_id的输出显示为 [对象,对象]...有人可以帮我抓取该数组中的所有内容吗?

谢谢一堆!!

JSON

中的location_id值不是"数组",而是"对象"。并且对象的默认字符串值为 [object Object] .因此,您需要将字符串与该对象的各个部分连接起来,而不是整个:

output += '<p>' + "Location: " + 
    val.location_id.longitude + ', ' + 
    val.location_id.latitude +
    '</p>';

或者,您可以获取整个location_id对象并字符串化 JSON。不过,这不会是人类可读的:

output += '<p>' + "Location: " + JSON.stringify(val.location_id) + '</p>';