27

i have a controller that returns an array of ActiveRecord objects and a jbuilder view to generate the json (all standard stuff). works great if i want for example an array of hashes.

so for example i have:

json.array!(@list) do |l|
    json.( l, :field )
end

which returns

[
  { "field": "one" },
  { "field": "two" },
  { "field": "three" }
]

however, i want just an array of strings; such that my json is

[
  "one",
  "two",
  "three"
]

whats should my jbuilder file be?

yee379
  • 6,498
  • 10
  • 56
  • 101

2 Answers2

60

A bit late but this will work:

json.array! @list

But consider to use it in a block to create a JSON pair:

json.data do
  json.array! @list  
end

# => { "data" : [ "item1", "item2", "item3" ] }
irmco
  • 924
  • 10
  • 13
  • thanks for the reply: i get a 'nil is not a symbol' error when trying either suggestion. however, when i do `json.array! @devices do |d| json.i d.device end`, it works (however, i have an array of anon hashes with single key 'i' then) – yee379 Jun 04 '13 at 23:17
  • 6
    Just try to create an Array of strings like `@devices.collect { |d| d.device }` and use this array to create the json. – irmco Jun 06 '13 at 13:18
  • 3
    You can also use pluck like `@devices.pluck :device` – Max Apr 03 '14 at 14:59
  • What if you want to grab things out of an object to put into an array? – j will Jan 06 '16 at 19:14
5

If you want Array as a value for some key, this will work:

json.some_key [1, 3, 4]
Ilya Novojilov
  • 871
  • 8
  • 12