在Rails 3.2.8中使用jbuilder模板生成的Pretty Print JSON [英] Pretty Print JSON generated with a jbuilder template in Rails 3.2.8

查看:135
本文介绍了在Rails 3.2.8中使用jbuilder模板生成的Pretty Print JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人有办法漂亮地打印jbuilder的JSON输出吗?

Anyone have a way to pretty print JSON output from jbuilder?

我可以使用以下类似的命令漂亮地打印控制器动作中生成的JSON:

I can pretty print JSON generated within a controller action with something like:

JSON.pretty_generate(some_json_object) 

但是一旦我使用了jbuilder模板,我就不知道一种可以漂亮地打印输出的方法.

but once I pass off to a jbuilder template, I'm not aware of a way to have that output pretty printed.

现在,我的操作方法的render语句很简单:

Right now, my action method's render statement is simple:

render formats: :json    

无论指定哪种输入格式类型(这都是我所希望的行为),这都能成功地强制使用jbuilder进行渲染.

And this successfully forces a rendering with jbuilder, regardless of input format type specified (which is my desired behavior).

推荐答案

我认为这很简单

@package = Package.first

json = JSON.parse(@blog.to_json)

PP.pp(json)

{"id_to_s"=>"5222675dbc11149e3a000002",
 "title"=>"Package Title",
 "version"=>"0.1.1",
 "comment"=>
  {"user"=>"Joe",
   "description"=>"Joe's comment"},
 "assets"=>
  [{"id_to_s"=>"522a4620fa451436f4000001",
    "_type"=>"Illustration",
    "start"=>0,
    "stop"=>100,
    "caption"=>"mountain climbing"},
   {"id_to_s"=>"522a56a6fa4514523a000001",
    "_type"=>"Illustration",
    "start"=>200,
    "stop"=>300,
    "caption"=>"airport"},
   {"id_to_s"=>"522a6a0ffa4514a30e000002",
    "_type"=>"Illustration",
    "start"=>400,
    "stop"=>600,
    "caption"=>"doc"},
   {"id_to_s"=>"522aa46bbc1114551f000001",
    "_type"=>"Illustration",
    "start"=>nil,
    "stop"=>nil,
    "caption"=>nil},
   {"id_to_s"=>"522aa47fbc1114551f000002",
    "_type"=>"Illustration",
    "start"=>10,
    "stop"=>30,
    "caption"=>"asdflkjsd"}]}

或者,更快的单线

PP.pp JSON.parse Blog.first.to_json

这篇关于在Rails 3.2.8中使用jbuilder模板生成的Pretty Print JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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