I have a big old config object. Something like:

var object = {
  item1: 'value1',
  item2: 1000,
  item3: ['a', 'b', 'c'],
  item4: [1, 2, 3],
  item5: {
    foo: 'bar'
  }
};

... 等等我想把它重写为有效的JSON,这样它就可以通过intertube传递,但我不想在文件中的每一行都手动添加双引号.当然,我不介意手动将整个内容包装在括号中,并将初始分配更改为第一个属性,但除此之外,我希望有一些资源可以完成繁重的工作.

不管怎样,如果你知道TextMate命令、regex技巧、在线转换器、友好的机器人,或者任何其他可以让这变得不那么乏味的东西,请帮助我.

推荐答案

  1. 启动Firefox/Chrome/Safari
  2. Open Firebug/developer tools
  3. Copy/paste your code into the console.
  4. 然后输入console.log(JSON.stringify(object)),瞧

  5. Copy/paste back into your text editor.

For more control over the formatting, I have a free online webpage:

http://phrogz.net/JS/NeatJSON

that lets you paste JSON or JS values in one box and see JSON at the bottom, with lots of knobs and sliders to adjust how it looks. For example, the JS value ["foo","bar",{dogs:42,piggies:0,cats:7},{jimmy:[1,2,3,4,5],jammy:3.14159265358979,hot:"pajammy"}] can be formatted like any of the following (and more):

[
    "foo",                            <- adjustable indentation
    "bar",
    {"dogs":42,"piggies":0,"cats":7}, <- small objects on one line!
    {
        "jimmy":[1,2,3,4,5],          <- small arrays on one line!
        "jammy":3.142,                <- decimal precision!
        "hot":"pajammy"
    }
]
[
  "foo",
  "bar",
  { "cats":7, "dogs":42, "piggies":0 }, <- spaces inside braces!
  {
    "hot":"pajammy",                    <- sort object keys!
    "jammy":3.14159265358979,
    "jimmy":[ 1, 2, 3, 4, 5 ]           <- spaces after commas!
  }
]
[ "foo",                           <- 'short' format puts first value
  "bar",                           <- on same line as opening bracket...
  { "dogs"    : 42,
    "piggies" : 0,                 
    "cats"    : 7 },               <- ...and close bracket with last value!
  { "jimmy" : [ 1, 2, 3, 4, 5 ],
    "jammy" : 3.14159265358979,    <- spaces around colons!
    "hot"   : "pajammy" } ]        <- align object values!

Screenshot of NeatJSON webpage

Json相关问答推荐

如何在JMESPath中区分空和假?

如何在改装Android中将ResponseBody转换为JSONObject

使用JQ在数组中 Select 第一个具有匹配项的项

使用JQ将JSON输出转换为CSV复杂 struct

在深度嵌套数组中使用布尔属性的jq-select

交换键和数组值,将旧键转换为新数组值,使用 jq

Android 如何判断小时时间是否在两个时间之间?

Groovy JsonBuilder 在for循环中添加数组元素

如何修复通过在 tsconfig.json 文件中添加allowImportingTsExtensions引发的错误 TS5023?

在 CodePipeline 中调用 lambda 时传递用户参数

Golang 解组行为:字段过多?

PowerShell - 如何迭代 PSCustomObject 嵌套对象?

可以通过 POST 使用 EventSource 传递参数的服务器发送事件 (SSE)

json.decoder.JSONDecodeError:期望值:第 1 行第 1 列(字符 0)

将json字符反序列化为枚举

将 javascript 对象或数组转换为 json 以获取 ajax 数据

Peewee 模型转 JSON

使用 application/json 优于 text/plain 的优势?

MySQL Select JSON 字段属性具有值的位置

从 Json 对象 Android 中获取字符串值