【问题标题】:complexJSON to HTML TablecomplexJSON 到 HTML 表
【发布时间】:2020-05-29 20:53:32
【问题描述】:

我知道这个问题被问了很多,但我就是忍不住,因为在我看来我的 JSON 有一些奇怪的格式。 我调用了您可以在下面看到的 bing api,它会报告如下 JSON:

{
  "authenticationResultCode": "ValidCredentials",
  "brandLogoUri": "http:dev.virtualearth.netBrandinglogo_powered_by.png",
  "copyright": "Copyright © 2020 Microsoft and its suppliers. All rights reserved. This API cannot be accessed and the content and any results may not be used, reproduced or transmitted in any manner without express written permission from Microsoft Corporation.",
  "resourceSets": [
    {
      "estimatedTotal": 44,
      "resources": [
        {
          "__type": "TrafficIncident:http:schemas.microsoft.comsearchlocalwsrestv1",
          "point": {
            "type": "Point",
            "coordinates": [
              48.12575,
              11.50249
            ]
          },
          "description": "Bei München-Laim - Stockender Verkehr;; vorsichtig an das Stauende heranfahren.",
          "end": "Date(1581665178000)",
          "incidentId": 1717453254024927000,
          "lastModified": "Date(1581643942010)",
          "roadClosed": false,
          "severity": 2,
          "source": 9,
          "start": "Date(1581061714000)",
          "toPoint": {
            "type": "Point",
            "coordinates": [
              48.12562,
              11.5046
            ]
          },
          "type": 2,
          "verified": true
        },
        {
          "__type": "TrafficIncident:http:schemas.microsoft.comsearchlocalwsrestv1",
          "point": {
            "type": "Point",
            "coordinates": [
              48.10819,
              11.61907
            ]
          },
          "description": "Bei Woferlstraße - Bauarbeiten auf Abschnitt.",
          "end": "Date(1581974827000)",
          "incidentId": 4267251995514645000,
          "lastModified": "Date(1581637098936)",
          "roadClosed": false,
          "severity": 2,
          "source": 9,
          "start": "Date(1581629269000)",
          "toPoint": {
            "type": "Point",
            "coordinates": [
              48.10819,
              11.61907
            ]
          },
          "type": 9,
          "verified": true
        },
        {
          "__type": "TrafficIncident:http:schemas.microsoft.comsearchlocalwsrestv1",
          "point": {
            "type": "Point",
            "coordinates": [
              48.14469,
              11.55741
            ]
          },
          "description": "Zwischen Karlstraße und Hirtenstraße - Bauarbeiten auf Abschnitt.",
          "end": "Date(1585778340000)",
          "incidentId": 3021451548046648000,
          "lastModified": "Date(1581637098936)",
          "roadClosed": false,
          "severity": 2,
          "source": 9,
          "start": "Date(1581629270000)",
          "toPoint": {
            "type": "Point",
            "coordinates": [
              48.14314,
              11.55658
            ]
          },
          "type": 9,
          "verified": true
        },
        {
          "__type": "TrafficIncident:http:schemas.microsoft.comsearchlocalwsrestv1",
          "point": {
            "type": "Point",
            "coordinates": [
              48.14314,
              11.58826
            ]
          },
          "description": "Bei Franz-Josef-Strauß-Ring - Baustelle.",
          "end": "Date(1609369140000)",
          "incidentId": 337182766905069500,
          "lastModified": "Date(1581637098936)",
          "roadClosed": false,
          "severity": 2,
          "source": 9,
          "start": "Date(1581629314000)",
          "toPoint": {
            "type": "Point",
            "coordinates": [
              48.14423,
              11.58316
            ]
          },
          "type": 9,
          "verified": true
        },
        {
          "__type": "TrafficIncident:http:schemas.microsoft.comsearchlocalwsrestv1",
          "point": {
            "type": "Point",
            "coordinates": [
              48.141,
              11.5613
            ]
          },
          "description": "Bei Karlsplatz - Bauarbeiten auf Abschnitt. Fahrbahn von auf einen Fahrstreifen verengt.",
          "end": "Date(1581974827000)",
          "incidentId": 1310817648090719700,
          "lastModified": "Date(1581637098936)",
          "roadClosed": false,
          "severity": 2,
          "source": 9,
          "start": "Date(1581629270000)",
          "toPoint": {
            "type": "Point",
            "coordinates": [
              48.14186,
              11.56163
            ]
          },
          "type": 9,
          "verified": true
        }
      ]
    }
  ]
}

我只是忍不住将描述部分放入一个简单的 html 表中。 以下是我现在尝试的。

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"> </script>
<script>
    $.getJSON("http://dev.virtualearth.net/REST/v1/Traffic/Incidents/48.052165,11.722993,48.222626,11.391344?key=BINGKEY").then(function(data)
{console.log(data);

   var tr = data
    for (var i = 0; i < data.resourceSets.estimatedTotal; i++) {
    var tr = $('<tr/>');

    // Indexing into data.report for each td element
    $(tr).append("<td>" + data.resourceSets.resources[i].description + "</td>");
    $('.table1').append(tr);
    }

});
</script>

<table class="table1">
    <tr>
        <th>description</th>
    </tr>
</table>
</body>
</html>

也许有人可以帮助我解决我的问题。 谢谢

【问题讨论】:

  • 您是否尝试过通过 json 验证器运行代码:jsonlint.com?您发布的 json 响应似乎确实缺少某些内容。它以逗号结尾...
  • 现在试过了,它说“有效的 JSON”
  • @Simon 我在下面的回复中实现了resolveField 函数。

标签: javascript html json


【解决方案1】:

在 javascript 中解析 json 并在 html 中显示该数据非常困难。Handlebars 是您解决方案的选项。从 API 生成的动态数据可以使用把手轻松嵌入。有关更多信息,请参阅下面的站点。希望这有帮助。

Introduction to Handlebars.js

【讨论】:

  • 不鼓励仅链接答案,您应该提供如何使用 Handlebars 解决问题的示例。此外,“很难解析 json ......并将其显示在表格中”非常大胆。 Sam am Polywhirl 先生的回答表明这实际上很容易(因为它是)
  • 从现在开始会关注它。谢谢。
【解决方案2】:

resourceSets 是 json 中的集合,您正尝试将其作为普通属性访问。

for(var s = 0; s < data.resourceSets.length; s++) {

    for (var i = 0; i < data.resourceSets[s].resources.length; i++) { 
        var tr = $('<tr/>');

        // Indexing into data.report for each td element
        $(tr).append("<td>" + data.resourceSets[s].resources[i].description + "</td>");
        $('.table1').append(tr);
    }
}

侧面但相关说明:估计总数为44,但在发布的json中,只有5个资源。您确定要迭代 44 次吗?如果是,则需要观察数组索引超出范围异常。

【讨论】:

  • 是的,我想显示所有项目,甚至可以更多。但我只需要描述信息,其余无关
  • 在这种情况下,您的 for 循环不应使用estimatedTotal 作为上限。我会更新答案
【解决方案3】:

我会声明一个可迭代的字段列表,然后动态循环资源。

[ 'description', 'severity', 'point.coordinates[0]', 'point.coordinates[1]' ]

注意:您可以通过映射附加多个项目,如下所示。

更新:您可以通过实现如下所示的递归函数来解析嵌套字段。

而不是这个:

return $('<td>').text(resource[field]);

你可以用这个:

return $('<td>').text(resolveField(resource, field));

警告:这不是万无一失的,因为它在多个嵌套数组中失败,例如foo[0][0].

演示

let fields = [ 'description', 'severity', 'point.coordinates[0]', 'point.coordinates[1]' ];
let data = getData();

$('.table-1 tbody').append(data.resourceSets.flatMap(resourceSet => {
  return resourceSet.resources.map(resource => {
    return $('<tr>').append(fields.map(field => {
      return $('<td>').text(resolveField(resource, field));
    }));
  });
}));

// Adapted from: https://stackoverflow.com/a/19156197/1762224
function resolveField(obj, prop) {
  return prop.match(/[^\]\[.]+/g)
    .map(token => {
      return Number.isInteger(token)
        ? parseInt(token, 10)
        : token.replace(/^['"](.+(?=['"]$))['"]$/, '$1');
    })
    .reduce((ref, curr) => {
      if (ref != null) {
        if (Array.isArray(ref)) {
          return ref[curr];
        } else if (typeof ref === 'object') {
          if (ref.hasOwnProperty(curr)) {
            return ref[curr];
          }
        }
      }
      return null;
    }, obj);
}

function getData() {
  return {
    "authenticationResultCode": "ValidCredentials",
    "brandLogoUri": "http:dev.virtualearth.netBrandinglogo_powered_by.png",
    "copyright": "Copyright © 2020 Microsoft and its suppliers. All rights reserved. This API cannot be accessed and the content and any results may not be used, reproduced or transmitted in any manner without express written permission from Microsoft Corporation.",
    "resourceSets": [{
      "estimatedTotal": 44,
      "resources": [{
          "__type": "TrafficIncident:http:schemas.microsoft.comsearchlocalwsrestv1",
          "point": {
            "type": "Point",
            "coordinates": [
              48.12575,
              11.50249
            ]
          },
          "description": "Bei München-Laim - Stockender Verkehr;; vorsichtig an das Stauende heranfahren.",
          "end": "Date(1581665178000)",
          "incidentId": 1717453254024927000,
          "lastModified": "Date(1581643942010)",
          "roadClosed": false,
          "severity": 2,
          "source": 9,
          "start": "Date(1581061714000)",
          "toPoint": {
            "type": "Point",
            "coordinates": [
              48.12562,
              11.5046
            ]
          },
          "type": 2,
          "verified": true
        },
        {
          "__type": "TrafficIncident:http:schemas.microsoft.comsearchlocalwsrestv1",
          "point": {
            "type": "Point",
            "coordinates": [
              48.10819,
              11.61907
            ]
          },
          "description": "Bei Woferlstraße - Bauarbeiten auf Abschnitt.",
          "end": "Date(1581974827000)",
          "incidentId": 4267251995514645000,
          "lastModified": "Date(1581637098936)",
          "roadClosed": false,
          "severity": 2,
          "source": 9,
          "start": "Date(1581629269000)",
          "toPoint": {
            "type": "Point",
            "coordinates": [
              48.10819,
              11.61907
            ]
          },
          "type": 9,
          "verified": true
        },
        {
          "__type": "TrafficIncident:http:schemas.microsoft.comsearchlocalwsrestv1",
          "point": {
            "type": "Point",
            "coordinates": [
              48.14469,
              11.55741
            ]
          },
          "description": "Zwischen Karlstraße und Hirtenstraße - Bauarbeiten auf Abschnitt.",
          "end": "Date(1585778340000)",
          "incidentId": 3021451548046648000,
          "lastModified": "Date(1581637098936)",
          "roadClosed": false,
          "severity": 2,
          "source": 9,
          "start": "Date(1581629270000)",
          "toPoint": {
            "type": "Point",
            "coordinates": [
              48.14314,
              11.55658
            ]
          },
          "type": 9,
          "verified": true
        },
        {
          "__type": "TrafficIncident:http:schemas.microsoft.comsearchlocalwsrestv1",
          "point": {
            "type": "Point",
            "coordinates": [
              48.14314,
              11.58826
            ]
          },
          "description": "Bei Franz-Josef-Strauß-Ring - Baustelle.",
          "end": "Date(1609369140000)",
          "incidentId": 337182766905069500,
          "lastModified": "Date(1581637098936)",
          "roadClosed": false,
          "severity": 2,
          "source": 9,
          "start": "Date(1581629314000)",
          "toPoint": {
            "type": "Point",
            "coordinates": [
              48.14423,
              11.58316
            ]
          },
          "type": 9,
          "verified": true
        },
        {
          "__type": "TrafficIncident:http:schemas.microsoft.comsearchlocalwsrestv1",
          "point": {
            "type": "Point",
            "coordinates": [
              48.141,
              11.5613
            ]
          },
          "description": "Bei Karlsplatz - Bauarbeiten auf Abschnitt. Fahrbahn von auf einen Fahrstreifen verengt.",
          "end": "Date(1581974827000)",
          "incidentId": 1310817648090719700,
          "lastModified": "Date(1581637098936)",
          "roadClosed": false,
          "severity": 2,
          "source": 9,
          "start": "Date(1581629270000)",
          "toPoint": {
            "type": "Point",
            "coordinates": [
              48.14186,
              11.56163
            ]
          },
          "type": 9,
          "verified": true
        }
      ]
    }]
  };
}
table { border-collapse: collapse; }
table, th, td { border: thin solid #AA5555; }
th, td { padding: 0.25em; }
thead tr { background: #EE8888; }
tbody tr:nth-child(even) { background: #EECCCC; }
tbody tr:nth-child(odd)  { background: #FFEEEE; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table-1">
  <thead>
  <tr>
    <th>Description</th>
    <th>Severity</th>
    <th>Lat</th>
    <th>Lon</th>
  </tr>
  </thead>
  <tbody>
  </tbody>
</table>

这是resolveField 函数的测试套件:

let foo1 = { bar : 10 };
let foo2 = { bar : { baz : [ 1, 2 ] } };
let foo3 = { bar : [ { baz : 1 }, { baz : 2 } ] };

console.log(resolveField(foo1, 'bar')        === 10);
console.log(resolveField(foo2, 'bar.baz[0]') ===  1);
console.log(resolveField(foo3, 'bar[1].baz') ===  2);

【讨论】:

    猜你喜欢
    • 2014-05-27
    • 2018-07-13
    • 1970-01-01
    • 2015-10-15
    • 1970-01-01
    • 1970-01-01
    • 2017-12-23
    • 2021-10-08
    • 2016-07-26
    相关资源
    最近更新 更多