如何将 JSON 中的键和值渲染到网格中

How to render keys and values from JSON into a grid

我有一个很大的 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>

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

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

是的,它总是打印最后一个!因为您没有在循环内附加元素,所以这就是为什么只有最后一个元素保存在 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);
}

输出