vue codemirror 取消autoFormatRange后如何做json格式化
方法一:JSON.stringify
this.codemirror.setValue((JSON.stringify(JSON.parse(jsonStr), null, 2)))
缺点:这样会造成数值类型值的精度丢失,如:
{
"a":1.000000000000000000,
"b":123455667111111111117
}
{a: 1, b: 123455667111111110000}
方法二:autoFormatRange
CodeMirror.defineExtension("autoFormatRange", function (from, to) {
var cm = this;
var outer = cm.getMode(), text = cm.getRange(from, to).split("\n");
var state = CodeMirror.copyState(outer, cm.getTokenAt(from).state);
var tabSize = cm.getOption("tabSize");
var out = "", lines = 0, atSol = from.ch == 0;
function newline() {
out += "\n";
atSol = true;
++lines;
}
for (var i = 0; i < text.length; ++i) {
var stream = new CodeMirror.StringStream(text[i], tabSize);
while (!stream.eol()) {
var inner = CodeMirror.innerMode(outer, state);
var style = outer.token(stream, state), cur = stream.current();
stream.start = stream.pos;
if (!atSol || /\S/.test(cur)) {
out += cur;
atSol = false;
}
if (!atSol && inner.mode.newlineAfterToken &&
inner.mode.newlineAfterToken(style, cur, stream.string.slice(stream.pos) || text[i+1] || "", inner.state))
newline();
}
if (!stream.pos && outer.blankLine) outer.blankLine(state);
if (!atSol) newline();
}
cm.operation(function () {
cm.replaceRange(out, from, to);
for (var cur = from.line + 1, end = from.line + lines; cur <= end; ++cur)
cm.indentLine(cur, "smart");
});
});
// Applies automatic mode-aware indentation to the specified range
CodeMirror.defineExtension("autoIndentRange", function (from, to) {
var cmInstance = this;
this.operation(function () {
for (var i = from.line; i <= to.line; i++) {
cmInstance.indentLine(i, "smart");
}
});
});
<textarea id=code><?=$value?></textarea>
<link rel="stylesheet" href="/codemirror/codemirror.css">
<script src="/codemirror/codemirror-compressed.js"></script>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById('code'), {
lineNumbers: true,
mode: "text/html"
});
var totalLines = editor.lineCount();
editor.autoFormatRange({line:0, ch:0}, {line:totalLines});
</script>
方法三:js-beautify
const beautify_js = require('js-beautify').js_beautify
const formattedJSON = beautify_js(jsonStr, { indent_size: 2 })
this.codemirror.setValue(formattedJSON)