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


当前回答

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

希望这有帮助!

其他回答

这里有一些东西来修饰这个老掉牙但很好的问题。如果您想将格式化的对象转储到控制台,但它仍像一团包裹的乱麻一样转储,隐藏字符如下???

'{\n    "_id": "630577bba145ff4f1",\n    "role": "user"}'

但你想要这种可爱??:

{
    "_id": "630557672d877bba145ff4f1",
    "role": "user"
}

诀窍是将JSON.stringify()包装在console.log()语句中。如果你讨厌打字,尝试构建代码段来完成繁重的工作。。。

如果您正在处理大型对象,这非常有用。

在浏览器开发工具中的“代码段”部分添加一个代码段,如下所示(更多…):

let o = <object to print>
console.log(JSON.stringify(o, null, 4))
console.log(o)

然后简单地替换为对象(可以从当前上下文中获得)并运行代码段。

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

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

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

如果您需要在文本区域中使用此选项,则接受的解决方案将不起作用。

<textarea id='textarea'></textarea>

$(“#textarea”).append(格式JSON(JSON.stringify(jsonobject),true));

function formatJSON(json,textarea) {
    var nl;
    if(textarea) {
        nl = "&#13;&#10;";
    } else {
        nl = "<br>";
    }
    var tab = "&#160;&#160;&#160;&#160;";
    var ret = "";
    var numquotes = 0;
    var betweenquotes = false;
    var firstquote = false;
    for (var i = 0; i < json.length; i++) {
        var c = json[i];
        if(c == '"') {
            numquotes ++;
            if((numquotes + 2) % 2 == 1) {
                betweenquotes = true;
            } else {
                betweenquotes = false;
            }
            if((numquotes + 3) % 4 == 0) {
                firstquote = true;
            } else {
                firstquote = false;
            }
        }

        if(c == '[' && !betweenquotes) {
            ret += c;
            ret += nl;
            continue;
        }
        if(c == '{' && !betweenquotes) {
            ret += tab;
            ret += c;
            ret += nl;
            continue;
        }
        if(c == '"' && firstquote) {
            ret += tab + tab;
            ret += c;
            continue;
        } else if (c == '"' && !firstquote) {
            ret += c;
            continue;
        }
        if(c == ',' && !betweenquotes) {
            ret += c;
            ret += nl;
            continue;
        }
        if(c == '}' && !betweenquotes) {
            ret += nl;
            ret += tab;
            ret += c;
            continue;
        }
        if(c == ']' && !betweenquotes) {
            ret += nl;
            ret += c;
            continue;
        }
        ret += c;
    } // i loop
    return ret;
}

出于调试目的,我使用:

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

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

它工作得很好:

console.table()

在此处阅读更多信息:https://developer.mozilla.org/pt-BR/docs/Web/API/Console/table