2

I am using rails 5 and i am using jbuilder for sending json. The problem i am facing is i want to merge 2 table json and send it to same key..

my json.jbuilder look like this

json.children env.sites do |site|
  json.nodeId "site_#{site.id}"
  json.type "site"
  json.extract! site,:id, :key, :name
  json.children site.networks do |network|
    json.nodeId "network_#{network.id}"
    json.type "network"
    json.extract! network,:id, :name
    json.children network.vlans do |vlan|
      json.type "vlan"
      json.extract! vlan,:id, :name
    end
  end
  json.children site.instances do |instance|
    json.type "host"
    json.extract! instance,:id, :name
    json.content do
      json.cpu instance.cpu
    end
  end
end

Issue i am facing over here is i want to merge site.networks and site.instaces in same key.. How i would achieve this..??

3
  • same key as in? what is the current and expected json output? Commented Jul 4, 2017 at 13:11
  • Current output is override the children key with site.instances data and expected is it should merge site.networks and site.instances json Commented Jul 4, 2017 at 13:16
  • it doesn't help much. You just can't merge anything..many of your keys are same, can you post expected json output? what needs to be array and what needs to be hash? Commented Jul 4, 2017 at 13:36

1 Answer 1

3

You can use json.array!

Try this,

json.children env.sites do |site|
  json.nodeId "site_#{site.id}"
  json.type "site"
  json.extract! site,:id, :key, :name
  json.children do
    json.array!(site.networks) do |network|
      json.nodeId "network_#{network.id}"
      json.type "network"
      json.extract! network,:id, :name
      json.children network.vlans do |vlan|
        json.type "vlan"
        json.extract! vlan,:id, :name
      end
    end
    json.array!(site.instances) do |instance|
      json.type "host"
      json.extract! instance,:id, :name
      json.content do
        json.cpu instance.cpu
      end
    end
  end
end
Sign up to request clarification or add additional context in comments.

1 Comment

The solution works but in my case, an additional requirement is for caching. Can I cache the 'site.networks' array in the above case as, # json.cache_collection! site.networks, key: 'site_network_array' do |network| ........ end

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.