javascript JSON 字符串化输出到多行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24515894/
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-10-28 02:57:36  来源:igfitidea点击:

JSON Stringify Ouput to Multiple Lines

javascriptjson

提问by Joey N

I'm writing a simple JS app that takes in a JSON file, displays the information to the user and allows them to modify it, and then allows them to re-export the JSON. However, the JSON that is being brought in is multi-line; each key/value is on its own line. When I use .stringifyto output the JSON, it all appears on one line. Is there any way for the stringify method to separate the lines?

我正在编写一个简单的 JS 应用程序,它接收一个 JSON 文件,向用户显示信息并允许他们修改它,然后允许他们重新导出 JSON。但是,引入的 JSON 是多行的;每个键/值都在自己的行上。当我.stringify用来输出 JSON 时,它都出现在一行上。stringify 方法有什么方法可以分隔行吗?

JSON Structure:

JSON 结构:

{"Title":
 {"lvlOne":[
  {"key":"val"},
  {"key":"val"},
  {"key":"val"}
 ],
 "lvl2":[
  {"key":"val"},
  {"key":"val"},
  {"key":"val"}
 ]}
}

But when I output, it all shows:

但是当我输出时,它都显示:

{"Title":{"lvlOne":[{"key":"val"},{"key":"val"},{"key":"val"}],"lvl2":[{"key":"val"{"key":"val"},{"key":"val"}]}}

回答by Mike Pelley

You can use the spaceparameter of the stringify method. From the official page, here is the relevant excerpt:

您可以使用stringify 方法space参数。从官方页面,这里是相关的摘录:

JSON.stringify({ a: 2 }, null, " ");   // '{\n "a": 2\n}'

回答by Maneesh Singh

you can also use.

你也可以使用。

var json = JSON.stringify({ uno: 1, dos : {"s":"dd","t":"tt"} }, null, '\t');
console.log(json);

回答by e sadeghi

its OK

没关系

JSON.stringify(JSON variable, null, "\t");