如何将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
相关产品推荐
相关产品推荐

