(json, options)
| 99 | |
| 100 | |
| 101 | export function formatJson (json, options) { |
| 102 | let reg = null; |
| 103 | let formatted = ''; |
| 104 | let pad = 0; |
| 105 | const PADDING = ' '; // one can also use '\t' or a different number of spaces |
| 106 | options = options || {}; |
| 107 | options.newlineAfterColonIfBeforeBraceOrBracket = |
| 108 | options.newlineAfterColonIfBeforeBraceOrBracket === true; |
| 109 | options.spaceAfterColon = options.spaceAfterColon !== false; |
| 110 | if (typeof json !== 'string') { |
| 111 | json = JSON.stringify(json); |
| 112 | } |
| 113 | json = JSON.parse(json); |
| 114 | json = JSON.stringify(json); |
| 115 | reg = /([\{\}])/g; |
| 116 | json = json.replace(reg, '\r\n$1\r\n'); |
| 117 | reg = /([\[\]])/g; |
| 118 | json = json.replace(reg, '\r\n$1\r\n'); |
| 119 | reg = /(\,)/g; |
| 120 | json = json.replace(reg, '$1\r\n'); |
| 121 | reg = /(\r\n\r\n)/g; |
| 122 | json = json.replace(reg, '\r\n'); |
| 123 | reg = /\r\n\,/g; |
| 124 | json = json.replace(reg, ','); |
| 125 | if (!options.newlineAfterColonIfBeforeBraceOrBracket) { |
| 126 | reg = /\:\r\n\{/g; |
| 127 | json = json.replace(reg, ':{'); |
| 128 | reg = /\:\r\n\[/g; |
| 129 | json = json.replace(reg, ':['); |
| 130 | } |
| 131 | if (options.spaceAfterColon) { |
| 132 | reg = /\:/g; |
| 133 | json = json.replace(reg, ': '); |
| 134 | } |
| 135 | json.split('\r\n').map(node => { |
| 136 | let i = 0; |
| 137 | let indent = 0; |
| 138 | let padding = ''; |
| 139 | if (node.match(/\{$/) || node.match(/\[$/)) { |
| 140 | indent = 1; |
| 141 | } else if (node.match(/\}/) || node.match(/\]/)) { |
| 142 | if (pad !== 0) { |
| 143 | pad -= 1; |
| 144 | } |
| 145 | } else { |
| 146 | indent = 0; |
| 147 | } |
| 148 | for (i = 0; i < pad; i++) { |
| 149 | padding += PADDING; |
| 150 | } |
| 151 | formatted += `${padding + node}\r\n`; |
| 152 | pad += indent; |
| 153 | }); |
| 154 | return formatted; |
| 155 | } |
| 156 | // 获取时间 fmt传格式如 'yyyy-MM-dd HH:mm:ss' |
| 157 | export function getNowTime (fmt) { |
| 158 | const date = new Date(); |
nothing calls this directly
no outgoing calls
no test coverage detected