Javascript 在 textarea 输入中美化 json 数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26320525/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:43:01  来源:igfitidea点击:

Prettify json data in textarea input

javascriptjqueryhtmlcssjson

提问by archytect

I've searched for this particular topic and couldn't find anything similar to it. If there is please close this and give a link.

我搜索了这个特定的主题,但找不到任何类似的东西。如果有请关闭这个并给出一个链接。

I'm creating a json data api simulator. I want users to be able to copy and paste a json object request into a textarea where they can also modify it before sending it to the server.

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

Problem is json obj copy and patses often results in extra spaces and is never aligned properly, even with the pre tag. I also want a good color scheme applied to keys and values.

问题是 json obj copy 和 patses 通常会导致额外的空格并且永远不会正确对齐,即使使用 pre 标记也是如此。我还想要一个很好的配色方案应用于键和值。

I've seen plugins, other questions and snippets of code, but they don't apply to textareas where the text is editable. Is there to keep it styled while in edit mode without it showing all the html tags that styled it? I want to be able to write it from scratch with javascript or jquery.

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

回答by Paul Sasik

The syntax highlighting is tough but check out this fiddle for pretty printing a json objectentered in a text area. Do note that the JSON has to be valid for this to work. (Use the dev console to catch errors.) Check jsLintfor valid json.

语法突出显示很难,但请查看此小提琴以漂亮地打印在文本区域中输入的 json 对象。请注意,JSON 必须有效才能工作。(使用开发控制台捕获错误。)检查jsLint以获取有效的 json。

The HTML:

HTML:

<textarea id="myTextArea" cols=50 rows=10></textarea>
<button onclick="prettyPrint()">Pretty Print</button>

The js:

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;
}

First try simple input like: {"a":"hello","b":123}

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

Simple pretty printing of JSON can be done rather easily. Try this js code: (jsFiddle here)

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

// 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;

For this HTML:

对于此 HTML:

<textarea id="myTextArea" cols=50 rows=25></textarea>

And check out JSON.stringify documentation.

并查看JSON.stringify 文档

回答by benshope

For the parsing step you're just going to want to JSON.parsethe contents of the textarea and handle any errors from bad input.

对于解析步骤,您只需要JSON.parse文本区域的内容并处理来自错误输入的任何错误。

For the formatting part of your question, Use JSON.stringify(blob, undefined, 2). Alternatively, if you need colors here is a simple JSON format/color component written in React:

对于问题的格式部分,请使用JSON.stringify(blob, undefined, 2). 或者,如果您需要颜色,这里是一个用 React 编写的简单 JSON 格式/颜色组件:

const HighlightedJSON = ({ json }: Object) => {
  const highlightedJSON = jsonObj =>
    Object.keys(jsonObj).map(key => {
      const value = jsonObj[key];
      let valueType = typeof value;
      const isSimpleValue =
        ["string", "number", "boolean"].includes(valueType) || !value;
      if (isSimpleValue && valueType === "object") {
        valueType = "null";
      }
      return (
        <div key={key} className="line">
          <span className="key">{key}:</span>
          {isSimpleValue ? (
            <span className={valueType}>{`${value}`}</span>
          ) : (
            highlightedJSON(value)
          )}
        </div>
      );
    });
  return <div className="json">{highlightedJSON(json)}</div>;
};

See it working in this CodePen: https://codepen.io/benshope/pen/BxVpjo

看看它在这个 CodePen 中的工作:https://codepen.io/benshope/pen/BxVpjo

Hope that helps!

希望有帮助!

回答by Alex Jolig

Here's a recursive function to return an object if it has been stringified multiple times:

这是一个递归函数,如果它被多次字符串化,则返回一个对象:

  const jsonPrettify = (json) => {
    if (typeof json === 'object' && json !== null) {
      const pretty = JSON.stringify(json, undefined, 4);
      return pretty;
    }

回答by Hyman

Late answer but modern one, use the secret intendation parameter.

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

I usually go for:

我通常去:

JSON.stringify(myData, null, 4);

JSON.stringify(myData, null, 4);



Here's the code definition, it explains it well.

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

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

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.
 */

回答by konalexiou

If you are a jquery fan, you can also use this small plugin i wrote:

如果你是 jquery 爱好者,你也可以使用我写的这个小插件:

// The plugin
$.fn.json_beautify= function() {
   var obj = JSON.parse( this.val() );
   var pretty = JSON.stringify(obj, undefined, 4);
   this.val(pretty);
};

// Then use it like this on any textarea
$('#myTextArea').json_beautify();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<textarea id="myTextArea" cols=50 rows=10>{"name":"John","age":30}</textarea>

回答by trekforever

I don't think that can be done with regular textareas. What you can do (and how most online code editors do it) is to create a transparent textarea that overlays on top of a div that contains the styled code. The user would still be able to type and interact with the input (and it fires the associated form events), and you can show syntax highlighting in the div that the user will visually see (see Textarea that can do syntax highlighting on the fly?)

我认为这不能用常规的 textareas 来完成。您可以做的(以及大多数在线代码编辑器是如何做的)是创建一个透明的文本区域,该区域覆盖在包含样式代码的 div 之上。用户仍然可以输入并与输入交互(并触发相关的表单事件),并且您可以在 div 中显示用户将在视觉上看到的语法突出显示(请参阅可以即时进行语法突出显示的 Textarea?)

Now as for JSON formatting, I would add custom events to the textarea so that when a user types or paste something, run it through a Javascript JSON prettifier (see How can I pretty-print JSON using JavaScript?) and then re-populate the div and textarea accordingly

现在至于 JSON 格式,我会将自定义事件添加到文本区域,以便当用户键入或粘贴某些内容时,通过 Javascript JSON 修饰符运行它(请参阅如何使用 JavaScript 漂亮地打印 JSON?),然后重新填充div 和 textarea 相应地