如果您(像我一样)发现 Ruby 的 JSON 库中内置的 pretty_generate 选项不够“漂亮”,我推荐我自己的 NeatJSON gem 用于格式化。
使用它gem install neatjson,然后使用JSON.neat_generate 而不是JSON.pretty_generate。
像 Ruby 的 pp 一样,它会在适合的情况下将对象和数组保持在一行,但根据需要包装成多个。例如:
{
"navigation.createroute.poi":[
{"text":"Lay in a course to the Hilton","params":{"poi":"Hilton"}},
{"text":"Take me to the airport","params":{"poi":"airport"}},
{"text":"Let's go to IHOP","params":{"poi":"IHOP"}},
{"text":"Show me how to get to The Med","params":{"poi":"The Med"}},
{"text":"Create a route to Arby's","params":{"poi":"Arby's"}},
{
"text":"Go to the Hilton by the Airport",
"params":{"poi":"Hilton","location":"Airport"}
},
{
"text":"Take me to the Fry's in Fresno",
"params":{"poi":"Fry's","location":"Fresno"}
}
],
"navigation.eta":[
{"text":"When will we get there?"},
{"text":"When will I arrive?"},
{"text":"What time will I get to the destination?"},
{"text":"What time will I reach the destination?"},
{"text":"What time will it be when I arrive?"}
]
}
它还支持多种formatting options,以进一步自定义您的输出。例如,冒号前后有多少个空格?逗号之前/之后?在数组和对象的括号内?您想对对象的键进行排序吗?你想让冒号都排成一行吗?
例如,使用您的示例哈希,您可以获得这些不同的输出,具体取决于您想要什么:
// JSON.neat_generate(o, wrap:true)
{
"a":"1",
"b":"2",
"c":"3",
"asefw":"dfsef"
}
// JSON.neat_generate o, wrap:true, aligned:true
{
"a" :"1",
"b" :"2",
"c" :"3",
"asefw":"dfsef"
}
// JSON.neat_generate o, wrap:true, aligned:true, around_colon:1
{
"a" : "1",
"b" : "2",
"c" : "3",
"asefw" : "dfsef"
}