javascript - 有没有用空格将 JSON 字符串化的函数?

标签 javascript json formatting

我知道 JSON 空格很重要这一事实。但是,仅对于调试输出,我想打印格式化的 JSON 对象,因此带有制表符和换行符。

JavaScript 中是否有用于格式化 JSON 字符串化的函数?

最佳答案

JSON.stringify 的第三个参数控制间距。所以你可以这样做,例如:

var o = {
  a: {c:34}
};

console.log(JSON.stringify(o, null, '\t'));

这个日志

{
    "a": {
        "c": 34
    }
} 

这个参数可以接受不同类型的值:

The space argument may be used to control spacing in the final string. If it is a number, successive levels in the stringification will each be indented by this many space characters (up to 10). If it is a string, successive levels will indented by this string (or the first ten characters of it).

Using a tab character mimics standard pretty-print appearance:

关于javascript - 有没有用空格将 JSON 字符串化的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16591742/

相关文章:

Javascript:在循环中使用 array.slice() 并且没有按预期工作

javascript - 如何将 ELSE 添加到要追加的 IF 语句

javascript - 如何使用http get返回值设置 Angular Controller 元素

c++ - 使用C++输出运算符打印前导零?

javascript - 更改图像单击上的选择框选择

javascript - 如何使用div id javascript添加增量值

formatting - 如何在 LaTeX 中给章节标题加下划线?

java - 如何使用表格格式将对象列表打印到文件

javascript - 为什么 ColdFusion 纪元时间比 javascript 纪元时间晚一小时?

java - Android firebase getValue() 不工作