title: How to reformat JSON in rails
body: <p>I am trying out d3.js from a rails app to give me pretty graphs. One of the graphs I am trying out is a <a href="http://bl.ocks.org/mbostock/4062045" rel="nofollow">forced directed graph</a>. In order to create this the JSON needs to be in the format</p>
  
  <pre><code>{
    "nodes":[
      {"name":"Myriel"},
      {"name":"Napoleon"},
      {"name":"Mlle.Baptistine"},
      {"name":"Mme.Magloire"}
   ],
  "links":[
      {"source":1,"target":0,"value":1},
      {"source":2,"target":0,"value":8},
      {"source":3,"target":0,"value":10},
      {"source":3,"target":2,"value":6}
  ]
  }
  </code></pre>
  
  <p>I currently have produced JSON from my database using this query:</p>
  
  <pre><code> User.joins("INNER JOIN relationships ON users.id = relationships.user_id").select(" users.name, relationships.source, relationships.target,relationships.value")
  </code></pre>
  
  <p>which was created in the controller as follows</p>
  
  <pre><code> def index
         render :json =&gt;  User.joins("INNER JOIN relationships ON users.id = relationships.user_id").select(" users.name, relationships.source, relationships.target,relationships.value")
    end
  end
  </code></pre>
  
  <p>and the result looks like this:</p>
  
  <pre><code>[{"name":"Myriel","source":121,"target":1,"value":1},{"name":"Napoleon","source":119,"target":2,"value":2},    {"name":"Myriel","source":121,"target":1,"value":2},{"name":"Myriel","source":121,"target":3,"value":1},{"name":"Mlle.Baptistine","source":122,"target":2,"value":3}]
  </code></pre>
  
  <p>Is there a simple way to map my JSON to what I need?</p>