【问题标题】:How to display JSON object with an array using jQuery如何使用 jQuery 显示带有数组的 JSON 对象
【发布时间】:2016-07-17 00:13:01
【问题描述】:

我正在使用 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 的输出显示为 [object, object]...有人可以帮我获取该数组中的所有内容吗?

非常感谢!!!

【问题讨论】:

    标签: javascript jquery arrays json parsing


    【解决方案1】:

    您在 JSON 中的 location_id 值不是“数组”,而是“对象”。 Object 的默认 String 值为[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>';
    

    【讨论】:

      猜你喜欢
      • 2021-06-15
      • 2020-03-30
      • 1970-01-01
      • 2018-03-30
      • 2023-02-15
      • 2016-01-21
      • 1970-01-01
      • 1970-01-01
      • 2012-03-31
      相关资源
      最近更新 更多