如何在React表格组件中将JSON数据渲染为易读的结构化展示形式
Hey there! Let's break down how to make that nested JSON data way more readable in your table. Here are two practical approaches based on your preferences:
This matches the structured layout you mentioned, using Row and Col components to organize the data into columns. First, we'll access the nested home object from your JSON, then render each value in its own column.
// First, safely access the nested data (parse if it's a JSON string) let serializedData; try { // Use this line if assessment.serialized is a string serializedData = JSON.parse(assessment.serialized); // If it's already an object, just use: // serializedData = assessment.serialized; } catch (error) { serializedData = null; } const homeData = serializedData?.app?.determination?.home; // Replace your original <td> with this: <td> {homeData ? ( <Row> <Col sm="4">{homeData.title}</Col> <Col sm="4">{homeData.createLabel}</Col> <Col sm="4">{homeData.createOrEditLabel}</Col> {/* Optional: Add more columns for extra fields */} <Col sm="4">{homeData.search}</Col> <Col sm="4">{homeData.notFound}</Col> </Row> ) : ( <span>No determination data available</span> )} </td>
Notes:
- We use optional chaining (
?.) to avoid errors if any part of the nested JSON structure is missing. - The try/catch block ensures we handle cases where
assessment.serializedmight be an invalid JSON string.
If you want a more compact, line-based or single-line display, you can format the data into readable key-value pairs. We'll add a small helper function to convert camelCase keys into user-friendly labels.
// Same data setup as above let serializedData; try { serializedData = JSON.parse(assessment.serialized); } catch (error) { serializedData = null; } const homeData = serializedData?.app?.determination?.home; // Helper to turn camelCase keys into human-readable labels const formatKey = (key) => { return key.replace(/([A-Z])/g, ' $1') // Add space before capital letters .replace(/^./, str => str.toUpperCase()); // Capitalize first letter }; // Replace your original <td> with this (line-based version): <td> {homeData ? ( <> {formatKey('title')}: {homeData.title} <br /> {formatKey('createLabel')}: {homeData.createLabel} <br /> {formatKey('createOrEditLabel')}: {homeData.createOrEditLabel} <br /> {formatKey('search')}: {homeData.search} <br /> {formatKey('notFound')}: {homeData.notFound} </> ) : ( <span>No determination data available</span> )} </td>
Single-Line Alternative:
If you prefer all values in one line like your example (Title -- create label -- create or edit label), use this instead inside the {homeData ? (...) : (...)} block:
`${homeData.title} -- ${homeData.createLabel} -- ${homeData.createOrEditLabel}`
内容的提问来源于stack exchange,提问作者cluis92

