Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a JSON having dynamic hash keys with jbuilder

Here I want to output json with dynamic group name rather than word group

@tickets.each do |group, v|
  json.group {
    json.array! v do |ticket|
      json.partial! 'tickets/ticket', ticket: ticket
    end}
end

Where @ticket is a hash like this

{a: [....], b: [.....]}

and I want output like this

{a: [
.....
],
b: [
....
]}
like image 332
Adnan Ali Avatar asked Feb 18 '15 22:02

Adnan Ali


1 Answers

Thanks to @AntarrByrd there is similar answer to this problem: JBuilder dynamic keys for model attributes

Using above logic I have solved this issue:

@tickets.each do |k, v|
    json.set! k do
      json.array!(v)do |ticket|
        json.partial! 'tickets/ticket', ticket: ticket
      end
    end
  end
like image 144
Adnan Ali Avatar answered Nov 15 '22 06:11

Adnan Ali