我如何以易于阅读(供人类阅读)的格式显示JSON?我主要寻找缩进和空白,甚至是颜色/字体样式等。


当前回答

这是user123444555621的很棒的HTML,适合终端。易于调试节点脚本:

function prettyJ(json) {
  if (typeof json !== 'string') {
    json = JSON.stringify(json, undefined, 2);
  }
  return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, 
    function (match) {
      let cls = "\x1b[36m";
      if (/^"/.test(match)) {
        if (/:$/.test(match)) {
          cls = "\x1b[34m";
        } else {
          cls = "\x1b[32m";
        }
      } else if (/true|false/.test(match)) {
        cls = "\x1b[35m"; 
      } else if (/null/.test(match)) {
        cls = "\x1b[31m";
      }
      return cls + match + "\x1b[0m";
    }
  );
}

用法:

// thing = any json OR string of json
prettyJ(thing);

其他回答

用户Pumbaa80的答案很好,如果你有一个想要漂亮打印的对象。如果要从一个有效的JSON字符串开始打印,需要首先将其转换为一个对象:

var jsonString = '{"some":"json"}';
var jsonPretty = JSON.stringify(JSON.parse(jsonString),null,2);  

这将从字符串构建一个JSON对象,然后使用JSON字符串的漂亮打印将其转换回字符串。

这很好:

https://github.com/mafintosh/json-markup来自马芬托什

const jsonMarkup = require('json-markup')
const html = jsonMarkup({hello:'world'})
document.querySelector('#myElem').innerHTML = html

HTML

<link ref="stylesheet" href="style.css">
<div id="myElem></div>

样式表示例可在此处找到

https://raw.githubusercontent.com/mafintosh/json-markup/master/style.css

下面是一个用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>;
};

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

希望这有帮助!

出于调试目的,我使用:

console.debug("%o", data);

https://getfirebug.com/wiki/index.php/Console_APIhttps://developer.mozilla.org/en-US/docs/DOM/console

更好的方法。

用Javascript美化JSON数组

JSON.stringify(jsonobj,null,'\t')