Json字符串的高亮显示 react-jsx
2021/6/3 10:21:18
本文主要是介绍Json字符串的高亮显示 react-jsx,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
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> 效果图:这篇关于Json字符串的高亮显示 react-jsx的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-12-31Vue CLI多环境配置学习入门
- 2024-12-31Vue CLI学习入门:一步一步搭建你的第一个Vue项目
- 2024-12-31Vue3公共组件学习入门:从零开始搭建实用组件库
- 2024-12-31Vue3公共组件学习入门教程
- 2024-12-31Vue3学习入门:新手必读教程
- 2024-12-31Vue3学习入门:初学者必备指南
- 2024-12-30Vue CLI多环境配置教程:轻松入门指南
- 2024-12-30Vue CLI 多环境配置教程:从入门到实践
- 2024-12-30初学者的vue CLI教程:快速开始你的Vue项目
- 2024-12-30Vue CLI教程:新手入门指南