7

I'm using json to store document versions of my data in postgresql. I would like to output an entire tree of objects with children, children of children etc and all attributes. If any attributes are added to any of the objects at a later date, I would like them to be include in subsequent json.

Is there any way to output the entire contents without having to least each and every attribute? ie not like this:

json.(object_name, :id, :attr1, :attr2.... etc)
juco
  • 6,331
  • 3
  • 25
  • 42
riley
  • 2,387
  • 1
  • 25
  • 31
  • Note: the [tag:jbuilder] tag’s description is wrong in this case. This question is about the [Jbuilder JSON DSL for Ruby](https://github.com/rails/jbuilder), not the [JBuilder Java IDE](http://www.embarcadero.com/products/jbuilder). – Rory O'Kane Aug 08 '13 at 19:50
  • “Output the entire contents” of what? What kind of object do you have that already contains a list of attributes? Is it a [`Hash`](http://www.ruby-doc.org/core-2.0/Hash.html)? – Rory O'Kane Aug 08 '13 at 20:42
  • 2
    I don't think there is. The whole idea behind JSON templates is that you get control over the what's exposed and what's not. Why don't you use `to_json`? – alf Aug 15 '13 at 17:13
  • Yes, you are right, no way to do this. Ended listing everything. – riley Oct 31 '13 at 23:05
  • @RoryO'Kane if you used `Hash` then just use `Hash` variable name `json.merge! HASH` – hiphapis Apr 14 '15 at 02:08

3 Answers3

10

I know this is an old thread, but I was wondering the same thing, and ended up here. Then I found a great answer here => How to extract all attributes with Rails Jbuilder?

@uiureo suggests to use json.merge!, and that worked perfactly for me :)

json.merge! object_name.attributes
Community
  • 1
  • 1
Hilde
  • 428
  • 5
  • 12
2

If you want your json to ouput like this:

{"id":1,"attribute1":1,"attribute2":2}

You can do this:

json.array! @my_object

However, if you want output that looks likes this:

{"my_object":{"id":1,"attribute1":1,"attribute2":2}}

You can do this:

json.my_object @my_object
Jason Denney
  • 3,191
  • 1
  • 18
  • 14
  • Can you explain a bit more what the ! does? – Chris Mar 28 '14 at 08:57
  • @Chris In Ruby, `.array!` is just a call to a method with the name `array!`, which is a different method from `array`. By convention, methods with names ending in `!` mutate the object, or are more permanent or dangerous. I am guessing that in this case, it indicates mutation of `json`. You would have to look up the documentation for the `#array!` method to see exactly what it does. – Rory O'Kane Apr 14 '15 at 02:24
0

You may look at json.except!

json.except! @resource, :id, :updated_at

json.except! @resource

https://github.com/chenqingspring/jbuilder-except

user2091375
  • 109
  • 1
  • 3