在textarea输入中美化json数据

时间:2021-03-07 18:15:11

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复制和补丁通常会产生额外的空间,而且永远不会正确对齐,即使是使用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从头编写它。

3 个解决方案

#1


65  

The syntax highlighting is tough but check out this fiddle for pretty printing a json object entered 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 jsLint for valid json.

语法突出显示很困难,但请查看这个小提琴,以便漂亮地打印输入在文本区域的json对象。请注意,JSON必须有效才能工作。(使用dev控制台捕捉错误。)检查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文档。

#2


0  

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?)

我不认为可以用常规的textarea来完成。您可以做的(以及大多数在线代码编辑器如何做)是创建一个透明的textarea,该textarea覆盖包含样式代码的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格式,我将向textarea添加自定义事件,以便当用户键入或粘贴某些内容时,通过Javascript JSON修饰符(参见如何使用Javascript漂亮地打印JSON ?)运行它,然后相应地重新填充div和textarea

#3


0  

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

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

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。另外,如果您需要颜色,这里有一个简单的JSON格式/颜色组件,用React表示:

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

可以看到它在这个代码页中工作:https://codepen.io/benshope/pen/BxVpjo

Hope that helps!

希望会有帮助!

#1


65  

The syntax highlighting is tough but check out this fiddle for pretty printing a json object entered 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 jsLint for valid json.

语法突出显示很困难,但请查看这个小提琴,以便漂亮地打印输入在文本区域的json对象。请注意,JSON必须有效才能工作。(使用dev控制台捕捉错误。)检查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文档。

#2


0  

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?)

我不认为可以用常规的textarea来完成。您可以做的(以及大多数在线代码编辑器如何做)是创建一个透明的textarea,该textarea覆盖包含样式代码的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格式,我将向textarea添加自定义事件,以便当用户键入或粘贴某些内容时,通过Javascript JSON修饰符(参见如何使用Javascript漂亮地打印JSON ?)运行它,然后相应地重新填充div和textarea

#3


0  

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

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

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。另外,如果您需要颜色,这里有一个简单的JSON格式/颜色组件,用React表示:

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

可以看到它在这个代码页中工作:https://codepen.io/benshope/pen/BxVpjo

Hope that helps!

希望会有帮助!