【问题标题】:How to render keys and values from JSON into a grid如何将 JSON 中的键和值呈现到网格中
【发布时间】:2021-08-15 05:03:19
【问题描述】:

我有一个大的 JSON 文件(示例如下),我正在尝试将其排列成格式良好的网格。这就是我现在拥有的:

const txt = '[{"prompts": "Breakfast","text": "The breakfast table is a microcosm of the wider world. How do we understand the people around us"},{"prompts": "Water Balloons","text": "This studio looks at the concept of water-balloons or rubber balloons"}]'


const obj = JSON.parse(txt);
let text = "";
for (let i = 0; i < obj.length; i++) {
  text = obj[i].prompts;
  names = obj[i].text;

}
  let prompt = document.createElement("div");
prompt.setAttribute("class", "box");
prompt.innerHTML = text;
document.getElementsByClassName("wrapper")[0].appendChild(prompt);

let output = document.createElement("div");
output.setAttribute("class", "box");
output.innerHTML = names;
document.getElementsByClassName("wrapper")[0].appendChild(output);
body {
  margin: 40px;
}

.box {
  background-color: #444;
  color: #fff;
  border-radius: 5px;
  padding: 20px;
  font-size: 150%;
}

.box:nth-child(even) {
  background-color: #ccc;
  color: #000;
}

    .wrapper {
        display: grid;
    grid-gap: 10px;
        grid-template-columns: repeat(1, minmax(100px,1fr) minmax(200px,2fr));
    }
<div class="wrapper">
  <div class="box">1</div>
  <div class="box">2</div>
</div>

但是,这只会打印最后一项:

我想打印所有项目,我做错了什么?键应在黑框中,值应在白框中。

【问题讨论】:

  • 这与 JSON 有什么关系呢? JSON.parse 可以工作,在这种情况下,这与 JSON 字符串无关,而您的问题是关于对象的标准数组,或者解析失败,在这种情况下,“为什么我的 JSON 不解析?”之后的所有内容。无关紧要。
  • @Mike'Pomax'Kamermans,我想这是有道理的。我想我可能做错了解析,如果有更好的方法来处理键和值。我会删除标签。
  • 如果 JSON.parse 没有抛出,那么这是您不需要担心的问题的一个方面,从您的问题中消除(少量)复杂性。现在你只需要继续:运行minimal reproducible example 练习,看看还有什么不是问题的一部分 =)

标签: javascript html css css-grid


【解决方案1】:

是的,它总是打印最后一个!因为您没有在循环内附加元素,所以这就是为什么只有最后一个元素保存在 textnames 变量中,请修改您的 JavaScript 代码,如下所示

const txt = '[{"prompts": "Breakfast","text": "The breakfast table is a microcosm of the wider world. How do we understand the people around us"},{"prompts": "Water Balloons","text": "This studio looks at the concept of water-balloons or rubber balloons"}]'


const obj = JSON.parse(txt);
for (let i = 0; i < obj.length; i++) {
  let text = obj[i].prompts;
  let names = obj[i].text;
  
  let prompt = document.createElement("div");
  prompt.setAttribute("class", "box");
  prompt.innerHTML = text;
  document.getElementsByClassName("wrapper")[0].appendChild(prompt);

  let output = document.createElement("div");
  output.setAttribute("class", "box");
  output.innerHTML = names;
  document.getElementsByClassName("wrapper")[0].appendChild(output);
}

输出

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-12
    • 2019-11-05
    • 2019-06-14
    • 2022-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多