在textarea输入中整理json数据

arc*_*ect 42 html javascript css jquery json

我搜索过这个特定的主题,找不到类似的东西.如果有请关闭此并给出一个链接.

我正在创建一个json数据api模拟器.我希望用户能够将json对象请求复制并粘贴到textarea中,他们也可以在将其发送到服务器之前对其进行修改.

问题是json obj复制和patses经常导致额外的空格,并且永远不会正确对齐,即使使用pre标签.我还想要一个适用于键和值的良好配色方案.

我已经看过插件,其他问题和代码片段,但它们不适用于文本可编辑的textareas.在编辑模式下是否保持样式,而不显示所有样式的html标签?我希望能够用javascript或jquery从头开始编写它.

Pau*_*sik 115

语法高亮是很难的,但请查看这个小提琴,以便相当打印在文本区域中输入的json对象.请注意,JSON必须对此有效.(使用开发控制台捕获错误.)检查jsLint是否有效的json.

HTML:

<textarea id="myTextArea" cols=50 rows=10></textarea>
<button onclick="prettyPrint()">Pretty Print</button>
Run Code Online (Sandbox Code Playgroud)

js:

function prettyPrint() {
    var ugly = document.getElementById('myTextArea').value;
    var obj = JSON.parse(ugly);
    var pretty = JSON.stringify(obj, undefined, 4);
    document.getElementById('myTextArea').value = pretty;
}
Run Code Online (Sandbox Code Playgroud)

首先尝试简单输入,如:{"a":"hello","b":123}

简单漂亮的JSON打印可以很容易地完成.试试这个js代码:(jsFiddle here)

// arbitrary js object:
var myJsObj = {a:'foo', 'b':'bar', c:[false,2,null, 'null']};

// using JSON.stringify pretty print capability:
var str = JSON.stringify(myJsObj, undefined, 4);

// display pretty printed object in text area:
document.getElementById('myTextArea').innerHTML = str;
Run Code Online (Sandbox Code Playgroud)

对于这个HTML:

<textarea id="myTextArea" cols=50 rows=25></textarea>
Run Code Online (Sandbox Code Playgroud)

并查看JSON.stringify文档.

  • JSON.stringify(obj,undefined,4)这就是我要找的东西.谢谢 (6认同)

Jac*_*ack 11

迟到但现代的答案,使用秘密意图参数。

我通常会去:

JSON.stringify(myData, null, 4);


这是代码定义,它解释得很好。

stringify(value: any, replacer?: (this: any, key: string, value: any) => any, space?: string | number): string;

/**
 * Converts a JavaScript value to a JavaScript Object Notation (JSON) string.
 * @param value A JavaScript value, usually an object or array, to be converted.
 * @param replacer An array of strings and numbers that acts as a approved list for selecting the object properties that will be stringified.
 * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.
 */
Run Code Online (Sandbox Code Playgroud)