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

查看:37
本文介绍了如何“漂亮"在 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?

推荐答案

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

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天全站免登陆