1 import React from 'react' 2 import styles from './json.less' 3 4 const indent = <span> </span> 5 6 const objectToJsonCode = (object = {}, objectKey = null, deepIndent = null, parentIsArray = false, isArray = false) => { 7 const result = Object.entries(object).map(([key, value], index, data) => { 8 if (value instanceof Array || value instanceof Object) { 9 return <> 10 {objectToJsonCode(value, key, <>{deepIndent}{indent}</>, object instanceof Array, value instanceof Array)} 11 {data.length === index + 1 ? null : ','} 12 <br/> 13 </> 14 } 15 const type = Object.prototype.toString.call(value) 16 let className = 'string' 17 switch (type) { 18 case '[object Boolean]': 19 className = 'boolean' 20 break 21 case '[object String]': 22 className = 'string' 23 break 24 case '[object Number]': 25 className = 'number' 26 break 27 default: 28 className = 'string' 29 } 30 return (<> 31 {deepIndent}{indent} 32 {isArray ? null : <span className={styles.key}>{`"${key}": `}</span>} 33 <span className={styles[className]}> 34 { 35 (() => { 36 let valueString 37 switch (className) { 38 case 'string': 39 valueString = `"${value}"` 40 break 41 case 'boolean': 42 valueString = value.toString() 43 break 44 default: 45 valueString = value 46 } 47 return valueString 48 })() 49 } 50 </span> 51 {data.length === index + 1 ? <br/> : ','} 52 {data.length !== index + 1 ? <br/> : null} 53 </>) 54 }) 55 56 if (object instanceof Array) { 57 return <> 58 {deepIndent} 59 {parentIsArray ? null : <span className={styles.key}>{objectKey === null ? '' : `"${objectKey}": `}</span>} 60 {result.length === 0 ? 61 <span>[]</span> : 62 <><span>[</span> <br/> {result} {deepIndent}<span>]</span></> 63 } 64 </> 65 } 66 return <> 67 {deepIndent} 68 {parentIsArray ? null : <span className={styles.key}>{objectKey === null ? '' : `"${objectKey}": `}</span>} 69 {result.length === 0 ? 70 <span>{'{}'}</span> : 71 <><span>{'{'}</span> <br/>{result} {deepIndent}<span>{'}'}</span></> 72 } 73 </> 74 } 75 76 export default objectToJsonCode
1 pre {outline: 1px solid #ccc; padding: 5px; margin: 5px; } 2 .string { color: green; } 3 .number { color: darkorange; } 4 .boolean { color: blue; } 5 .null { color: magenta; } 6 .key { color: red; }
使用:
<pre style={{maxWidth:'640px'}}>{objectToJsonCode(jsonString)}</pre> 效果图: