如何“漂亮"在Ruby on Rails中格式化JSON输出 [英] How to "pretty" format JSON output in Ruby on Rails

查看:121
本文介绍了如何“漂亮"在Ruby on Rails中格式化JSON输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望Ruby on Rails中的JSON输出是漂亮的"或格式正确的.

I would like my JSON output in Ruby on Rails to be "pretty" or nicely formatted.

现在,我呼叫to_json,而我的JSON都在一行上.有时很难发现JSON输出流中是否有问题.

Right now, I call to_json and my JSON is all on one line. At times this can be difficult to see if there is a problem in the JSON output stream.

是否可以通过配置使我的JSON漂亮"或在Rails中很好地格式化?

Is there way to configure to make my JSON "pretty" or nicely formatted in Rails?

推荐答案

使用JSON更高版本中内置的pretty_generate()函数.例如:

Use the pretty_generate() function, built into later versions of JSON. For example:

require 'json'
my_object = { :array => [1, 2, 3, { :sample => "hash"} ], :foo => "bar" }
puts JSON.pretty_generate(my_object)

哪个会吸引您:

{
  "array": [
    1,
    2,
    3,
    {
      "sample": "hash"
    }
  ],
  "foo": "bar"
}

这篇关于如何“漂亮"在Ruby on Rails中格式化JSON输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆