New file |
| | |
| | | import React, { useState, useRef, useEffect } from 'react'; |
| | | import { Box, Typography, Paper } from '@mui/material'; |
| | | |
| | | const parseJson = (jsonStr) => { |
| | | let json = ''; |
| | | try { |
| | | const jsonObj = typeof jsonStr === 'string' ? JSON.parse(jsonStr) : jsonStr; |
| | | json = JSON.stringify(jsonObj, null, 2); |
| | | } catch (error) { |
| | | json = 'Invalid JSON'; |
| | | } |
| | | return json; |
| | | } |
| | | |
| | | const renderFormattedJson = (json) => { |
| | | const regex = /("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(\.\d*)?([eE][+\-]?\d+)?) /g; |
| | | const parts = json.split(regex); |
| | | |
| | | return parts.map((part, index) => { |
| | | if (!part) return null; |
| | | let style = {}; |
| | | |
| | | if (/^"/.test(part)) { |
| | | if (/:$/.test(part)) { |
| | | style = { color: '#b22222' }; // key |
| | | } else { |
| | | style = { color: '#1e90ff' }; // string |
| | | } |
| | | } else if (/true|false/.test(part)) { |
| | | style = { color: '#228B22' }; // boolean |
| | | } else if (/null/.test(part)) { |
| | | style = { color: '#808080' }; // null |
| | | } else if (/^-?\d+/.test(part)) { |
| | | style = { color: '#FF8C00' }; // number |
| | | } |
| | | |
| | | return ( |
| | | <span key={index} style={style}> |
| | | {part} |
| | | </span> |
| | | ); |
| | | }); |
| | | |
| | | }; |
| | | |
| | | const JsonShow = ({ data, height = 500 }) => { |
| | | let json = parseJson(data); |
| | | |
| | | return ( |
| | | <Paper |
| | | elevation={3} |
| | | sx={{ |
| | | padding: 2, |
| | | maxHeight: height, |
| | | overflow: 'auto', |
| | | backgroundColor: '#f5f5f5', |
| | | borderRadius: 2, |
| | | }} |
| | | > |
| | | <pre style={{ margin: 0, fontFamily: 'monospace', whiteSpace: 'pre-wrap' }}> |
| | | {json === 'Invalid JSON' ? ( |
| | | <Typography color="error">Invalid JSON</Typography> |
| | | ) : ( |
| | | renderFormattedJson(json) |
| | | )} |
| | | </pre> |
| | | </Paper> |
| | | ); |
| | | |
| | | } |
| | | |
| | | export default JsonShow; |