编程语言
首页 > 编程语言> > 如何在Javascript和HTML中格式化JSON?

如何在Javascript和HTML中格式化JSON?

作者:互联网

对于以下Google JSON-LD结构……

<script type="application/ld+json" id="datablock-1">
{
  "@context": "http://schema.org/",
  "@type": "Person",
  "honorificPrefix": "Dr",
  "givenName": "Albert",
  "familyName": "Einstein",
  "honorificSuffix": "PhD",
  "jobTitle": "Professor of Physics",
  "worksFor": [ {
      "@type": "EducationalOrganization",
      "department": "School of Science",
      "parentOrganization": "Princeton University",
      "address": [ {
          "@type": "PostalAddress",
          "streetAddress": "One Relativity Way",
          "addressCountry": "USA" } ]
    } ]
}
</script>

这个HTML JavaScript工作原理:

<body>
    <dl><dt>Big Ideas</dt><dd id="dd-1"></dd></dl>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
    var data = $("#datablock-1").html();
    var json = JSON.parse(data);
    var people = json["worksFor"];
    for (i=0; i<=people.length; i++) {
        var a=json["givenName"];
        var b=json["familyName"];
        var c=json["honorificSuffix"];
        var d=json["worksFor"][i]["parentOrganization"];
        $('#dd-1').append("<dd>"+a+" "+b+", "+c+". "+" "+d+"."+" "+"</dd>");
    }
</script>
</body>

现在我需要在对象中更深入一级并添加有关“@type”的信息:“PostalAddress”.

但是这个HTML JavaScript不起作用:

<body>
    <dl><dt>Big Ideas</dt><dd id="dd-1"></dd></dl>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
    var data = $("#datablock-1").html();
    var json = JSON.parse(data);
    var people = json["worksFor"]["address"];
    for (i=0; i<=people.length; i++) {
        var a=json["givenName"];
        var b=json["familyName"];
        var c=json["honorificSuffix"];
        var d=json["worksFor"][i]["parentOrganization"];
        var e=json["worksFor"]["address"][i]["streetAddress"];
        $('#dd-1').append("<dd>"+a+" "+b+", "+c+". "+" "+d+"."+" "+e+"</dd>");
    }
</script>
</body>

我究竟做错了什么?如何纠正错误?

解决方法:

难道你不是只是从顶部跳到邮政地址,而不改变条件?我已经将你的人员变量名称改为works,因为这是你正在迭代的内容,因为它看起来不像你有一个人的列表atm.也许我错了?

<body>
    <dl><dt>Big Ideas</dt><dd id="dd-1"></dd></dl>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
    var data = $("#datablock-1").html();
    var json = JSON.parse(data);
    var worksFor= json["worksFor"];
    for (i=0; i<=worksFor.length; i++) {
        var a=json["givenName"];
        var b=json["familyName"];
        var c=json["honorificSuffix"];
        var d=json["worksFor"][i]["parentOrganization"];
        var e=json["worksFor"][i]["address"][0]["streetAddress"];//this line is changed
        $('#dd-1').append("<dd>"+a+" "+b+", "+c+". "+" "+d+"."+e+"</dd>");
    }
</script>
</body>

标签:json-ld,javascript,json
来源: https://codeday.me/bug/20190829/1762489.html