【问题标题】:Trying to access json content and display in a grid fashion尝试访问 json 内容并以网格方式显示
【发布时间】:2019-06-04 15:07:43
【问题描述】:

我有一个包含以下内容的 JSON 文件。

{
    "rooms":[
      {
        "id": "1",
        "name": "living",
        "Description": "The living room",
         "backgroundpath":"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSrsU8tuZWySrSuRYdz72WWFiYaW5PCMIwPAPr_xAIqL-FgmQ4qRw",       
         "Settings": {
          "Sources": [
            {
              "srcname":["DirectTV","AppleTV","Sonos"],
              "iconpath":["src/assets/images/ThemeEditorImgLib_iTVLight5d3a46c1ad5d7796.png","path2"]
            }
            ],
          "hex": "#000"
          }
      },
      {
        "id": "2",
        "name": "dining",
        "Description": "The Dining room",
        "backgroundpath":"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTjjspDkQEzbJJ1sSLS2ReWEx5P2ODNQmOtT572OIF9k3HbTGxV",
        "Settings": {
          "Sources": [
            {
              "srcname":["Climate","Shades"],
              "iconpath":["path1","path2"]
            }
            ],
          "hex": "#000"
        }
      }
]
}

我的 HTML 文件有:

<div class="roww">
<div class="col-md-4 col-sm-6 col-12">

</div>
 </div>

我想在 HTML 中显示我的 JSON 内容。 到目前为止,我已经尝试了以下方法。

private initTileGrid():void
  {

    var col = document.getElementsByClassName("roww")[0];

    var outeritems=this.room_list.rooms;
   // console.log(outeritems);
    for(var i=0;i<outeritems.length;i++){
      var tile = document.getElementsByClassName("col-md-4 col-sm-6 col-12 tile no-padding")[0];
     var outerdiv = document.createElement("div");
      var h5 = document.createElement("h5");
      h5.innerHTML = outeritems[i].Description;
      outerdiv.appendChild(h5);
      var p = document.createElement("p");
      p.innerHTML = outeritems[i].name;
      outerdiv.appendChild(p);
     // col.appendChild(outerdiv);
      tile.appendChild(outerdiv);
      var inneritem=outeritems[i].Settings.Sources.srcname;
      console.log(inneritem);
      var innerdiv = document.createElement("div");
      for(var j=0;j<inneritem.length;j++)
      {
        console.log("hi")
        var h5inner = document.createElement("h5");
        h5inner.innerHTML = inneritem.srcname; 
        console.log(h5inner);
        innerdiv.appendChild(h5inner);
      }
tile.appendChild(innerdiv);
    }

我能够显示来自 json 的描述和名称,但无法获取源列表。

我的最终解决方案应该是一个网格,其瓦片数量等于 JSON 中的对象数量,每个瓦片都有来自 json 及其内容的背景图像。

谁能告诉我哪里出错了? 任何帮助表示赞赏!

【问题讨论】:

  • 对此进行了尝试,并意识到您在 JSON 中的 sources 可能结构不正确。 JSON是你建的吗?你也在使用typescript吗?因为private initTileGrid():void 也不对。 sources 是一个带有子数组的数组,但它最好作为一个object 的数组
  • 是的,JSON 是由我构建的,我使用 JSON 验证器在线检查我的 JSON,所以我认为它是正确的。是的,我正在使用打字稿,我正在研究 Angular。你能告诉我如何更好地构建它吗?
  • 它是有效的 JSON。但是有效和最合适是不同的。要我在下面发布建议的更改吗?
  • 是否也可以为每个 srcname 映射一个图标(来自 iconpath)?@Bibberty
  • @Bibberty 是的,这真的很有帮助,谢谢 :)

标签: javascript json angular dom


【解决方案1】:

我建议并推荐使用Template Literals 以下列方式生成您的动态 HTML。

使用Array#mapArray#joinDestructuring assignment

const data = {"rooms":[{"id":"1","name":"living","Description":"The living room","backgroundpath":"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSrsU8tuZWySrSuRYdz72WWFiYaW5PCMIwPAPr_xAIqL-FgmQ4qRw","Settings":{"Sources":[{"srcname":["DirectTV","AppleTV","Sonos"],"iconpath":["src/assets/images/ThemeEditorImgLib_iTVLight5d3a46c1ad5d7796.png","path2"]}],"hex":"#000"}},{"id":"2","name":"dining","Description":"The Dining room","backgroundpath":"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTjjspDkQEzbJJ1sSLS2ReWEx5P2ODNQmOtT572OIF9k3HbTGxV","Settings":{"Sources":[{"srcname":["Climate","Shades"],"iconpath":["path1","path2"]}],"hex":"#000"}}]}

const res = data.rooms.map(({name, Description, Settings:{Sources}})=>{
  
  const inner = Sources.map(({srcname})=>{
    return srcname.map(src=>`<h5>${src}</h5>`).join("");
  }).join("");

  return `
    <div>
      <h5>${Description}</h5>
      <p>${name}</p>
      <div class="inner">
         ${inner}
      </div>
    </div>
  `
}).join("");

document.body.innerHTML = res;
body&gt;div{background-color:lightgrey;padding:5px;margin-top:5px}body&gt;div::before{content:"row"}body&gt;div&gt;*{margin-left:10px}h5{background-color:blue;color:white;padding:5px}h5::before{content:"outer h5:: "}p{background-color:purple;color:white;padding:5px}p::before{content:"p:: "}div.inner{padding:5px;background-color:grey}div.inner::before{content:"inner div"}div.inner&gt;h5{background-color:green;color:white}div.inner&gt;h5::before{content:"inner h5:: "}

未缩小的 CSS:

body > div {
  background-color: lightgrey;
  padding: 5px;
  margin-top: 5px;
}

body > div::before {
  content: "row";
}

body > div > * {
  margin-left: 10px;
}

h5 {
  background-color: blue;
  color: white;
  padding: 5px;
}

h5::before {
  content: "outer h5:: "
}

p {
  background-color: purple;
  color: white;
  padding: 5px;
}

p::before {
  content: "p:: ";
}

div.inner {
  padding: 5px;
  background-color: grey;
}

div.inner::before {
  content: "inner div";
}

div.inner > h5 {
  background-color: green;
  color: white;
}

div.inner > h5::before {
  content: "inner h5:: "
}

【讨论】:

  • 谢谢,我也试试这个方法:)
【解决方案2】:

V_Stack 如前所述,这只是我对 JSON 的源代码部分所做的调整,向前推进它将使处理源代码变得更容易,尤其是在添加其他属性时。请注意,它现在是一个自包含对象的数组。

{
  "rooms": [{
      "id": "1",
      "name": "living",
      "Description": "The living room",
      "backgroundpath": "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSrsU8tuZWySrSuRYdz72WWFiYaW5PCMIwPAPr_xAIqL-FgmQ4qRw",
      "Settings": {
        "Sources": [{
            "srcname": "DirectTV",
            "iconpath": "src/assets/images/ThemeEditorImgLib_iTVLight5d3a46c1ad5d7796.png"
          },
          {
            "srcname": "AppleTV",
            "iconpath": "path2"
          },
          {
            "srcname": "Sonos",
            "iconpath": ""
          }
        ],
        "hex": "#000"
      }
    },
    {
      "id": "2",
      "name": "dining",
      "Description": "The Dining room",
      "backgroundpath": "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTjjspDkQEzbJJ1sSLS2ReWEx5P2ODNQmOtT572OIF9k3HbTGxV",
      "Settings": {
        "Sources": [{
            "srcname": "Climate",
            "iconpath": "path1"
          },
          {
            "srcname": "Shades",
            "iconpath": "path2"
          }
        ],
        "hex": "#000"
      }
    }
  ]
}

【讨论】:

    【解决方案3】:

    试试这个:

    var col = document.getElementsByClassName("roww")[0];
    
    var outeritems = this.room_list.rooms;
    // console.log(outeritems);
    for (var i = 0; i < outeritems.length; i++) {
      var tile = document.getElementsByClassName("col-md-4")[0];
      var outerdiv = document.createElement("div");
      var h5 = document.createElement("h5");
      h5.innerHTML = outeritems[i].Description;
      outerdiv.appendChild(h5);
      var p = document.createElement("p");
      p.innerHTML = outeritems[i].name;
      outerdiv.appendChild(p);
      // col.appendChild(outerdiv);
      tile.appendChild(outerdiv);
      outeritems[i].Settings.Sources.forEach(source => {
    
        var inneritem = source.srcname;
        console.log(inneritem);
        var innerdiv = document.createElement("div");
        for (var j = 0; j < inneritem.length; j++) {
          console.log("hi")
          var h5inner = document.createElement("h5");
          h5inner.innerHTML = inneritem[j];
          console.log(h5inner);
          innerdiv.appendChild(h5inner);
        }
        tile.appendChild(innerdiv);
      });
    }
    

    }

    你需要遍历Settings.Sources和srcname,因为它们都是数组

    【讨论】:

      【解决方案4】:

      您的主要问题从这一行开始 var inneritem=outeritems[i].Settings.Sources.srcname; Sources 是一个数组,因此您需要像 Sources[j] 一样访问它,其中 j 是数组长度内的一个数字。

      内循环没问题,你只需要正确循环Sources

      我还必须向瓦片类添加类以匹配您的 getElementsByClassName 查询

      const room_list = {
        "rooms": [{
            "id": "1",
            "name": "living",
            "Description": "The living room",
            "backgroundpath": "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSrsU8tuZWySrSuRYdz72WWFiYaW5PCMIwPAPr_xAIqL-FgmQ4qRw",
            "Settings": {
              "Sources": [{
                "srcname": ["DirectTV", "AppleTV", "Sonos"],
                "iconpath": ["src/assets/images/ThemeEditorImgLib_iTVLight5d3a46c1ad5d7796.png", "path2"]
              }],
              "hex": "#000"
            }
          },
          {
            "id": "2",
            "name": "dining",
            "Description": "The Dining room",
            "backgroundpath": "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTjjspDkQEzbJJ1sSLS2ReWEx5P2ODNQmOtT572OIF9k3HbTGxV",
            "Settings": {
              "Sources": [{
                "srcname": ["Climate", "Shades"],
                "iconpath": ["path1", "path2"]
              }],
              "hex": "#000"
            }
          }
        ]
      }
      
      var col = document.getElementsByClassName("roww")[0];
      
      var outeritems = room_list.rooms;
      // console.log(outeritems);
      for (var i = 0; i < outeritems.length; i++) {
        var tile = document.getElementsByClassName("col-md-4 col-sm-6 col-12 tile no-padding")[0];
        var outerdiv = document.createElement("div");
        var h5 = document.createElement("h5");
        h5.innerHTML = outeritems[i].Description;
        outerdiv.appendChild(h5);
        var p = document.createElement("p");
        p.innerHTML = outeritems[i].name;
        outerdiv.appendChild(p);
        // col.appendChild(outerdiv);
        tile.appendChild(outerdiv);
        var inneritems = outeritems[i].Settings.Sources
        var innerdiv = document.createElement("div");
        for (var j = 0; j < inneritems.length; j++) {
          var inneritem = inneritems[j];
          var h5inner = document.createElement("h5");
          h5inner.innerHTML = inneritem.srcname;
          innerdiv.appendChild(h5inner);
        }
        tile.appendChild(innerdiv);
      }
      <div class="roww">
        <div class="col-md-4 col-sm-6 col-12 tile no-padding">
      
        </div>
      </div>

      【讨论】:

      • 这确实有效,但仍不能以网格格式显示。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-01
      • 1970-01-01
      相关资源
      最近更新 更多