You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将JSON数据转换为HTML?JSON数组转HTML实现求助

Convert JSON Array to Target HTML Structure

Got it, let’s work through this together. First, let’s unpack your JSON structure—we need to access the title values nested in data.posts.edges[].node, then wrap each title in an <h1> tag inside a parent <div>.

Here are practical solutions for different common scenarios:

1. Vanilla JavaScript (Direct DOM Manipulation)

If you’re working with plain JS and want to build DOM elements directly:

// Your raw JSON data
const jsonData = { 
  "data": { 
    "posts": { 
      "edges": [ 
        { "node": { "title": "Hello World" } }, 
        { "node": { "title": "How to do Online Payment" } }, 
        { "node": { "title": "What is good programme language?" } } 
      ] 
    } 
  } 
};

// Extract the array of post entries
const postEdges = jsonData.data.posts.edges;

// Create the parent div container
const containerDiv = document.createElement('div');

// Loop through each entry to build h1 elements
postEdges.forEach(edge => {
  const titleElement = document.createElement('h1');
  titleElement.textContent = edge.node.title;
  containerDiv.appendChild(titleElement);
});

// Add the finished container to your page (e.g., the body)
document.body.appendChild(containerDiv);

2. Vanilla JavaScript (Generate HTML String)

If you prefer to create an HTML string first (great for inserting into innerHTML):

const jsonData = { 
  "data": { 
    "posts": { 
      "edges": [ 
        { "node": { "title": "Hello World" } }, 
        { "node": { "title": "How to do Online Payment" } }, 
        { "node": { "title": "What is good programme language?" } } 
      ] 
    } 
  } 
};

// Map each entry to an h1 string, then combine them
const titleHtml = jsonData.data.posts.edges
  .map(edge => `<h1>${edge.node.title}</h1>`)
  .join('');

// Wrap in the parent div
const finalHtml = `<div>${titleHtml}</div>`;

// Insert into your page (replace 'target-container' with your element ID)
document.getElementById('target-container').innerHTML = finalHtml;

3. React Component

If you’re using React, you can render the structure directly in a component:

function PostTitleList({ data }) {
  return (
    <div>
      {/* Use a unique post ID as the key if available (index is a fallback) */}
      {data.posts.edges.map((edge, index) => (
        <h1 key={index}>{edge.node.title}</h1>
      ))}
    </div>
  );
}

// Usage example: pass your JSON's 'data' property to the component
<PostTitleList data={jsonData.data} />

All these methods will produce exactly the HTML structure you need, with each post title wrapped in an <h1> inside a parent <div>.

内容的提问来源于stack exchange,提问作者Yosua Michael

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:27:29