简体   繁体   中英

How to encode JSON hash using JBuilder in Rails?

There is 'groups' hash, when key of the hash is name of some group, and value of the hash is an array of some items. I want to encode it into JSON, but I can't event encode name of key in hash, because it's not contanstant:

x = Jbuilder.encode do |json|
  groups.each do |k, v|     
    json.set!(:group, k)
    json.group k    
  end
end

May be you suggest me how to execute method of 'json' using dynamic name?

Use the array! method :

json.array!(groups) do |json, group|
    json.set!(group.name, array)
end

Edit: For a hash of groups with each group's name as its key, do this:

groups.each do |group|
    json.set!(group.name, array)
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM