d3 reading JSON data in Rails app

900 views
Skip to first unread message

Patrick Johnson

unread,
Oct 16, 2013, 4:34:57 PM10/16/13
to d3...@googlegroups.com
Hey all, 

Huge thanks for any help from this group. 

So I'm running into an issue in my rails app when it comes to using d3. Currently, I can't get the data to display from within the rails app. 

We are generating the json data via rails, then within the particular view, trying to access it with d3. 

EX: 
// assigning the json data to a variable
var data = <%= raw(bar_chart_report.data.to_json) %>;

// trying to access that data with d3
d3.json(data, function(error, data){
    if (error) {alert('error');}
    else {console.log(data);}
    });


I've ran a quick for/loop to make sure the data is obtainable via JS in general, and so far so good. I just can't access the data when using d3. Curious if anyone has some knowledge to help lead me in the right direction. 

Thanks!

Nanda Yadav

unread,
Oct 16, 2013, 10:53:55 PM10/16/13
to d3...@googlegroups.com
The d3.json requires first parameter to be a url/endpoint that returns the json data. What you could is have a dedicate endpoint in rails app controller to return that json data, which d3.json can call to. sth like this:

//Controller action
def bar_chart
  respond_to do |format|
    format.any { render :json => bar_chart_report.data.to_json }
  end
end

then on js side, (assuming route is defined as bar_chart in routes.rb
d3.json("/bar_chart", function(error, data){ 
  //do sth
});

Phuoc Do

unread,
Oct 18, 2013, 3:19:54 PM10/18/13
to d3...@googlegroups.com
You can also use format.json:

respond_to do |format|
  format.json { render :json => bar_chart_report.data.to_json }
end

Akram Khan

unread,
Nov 6, 2013, 6:25:36 AM11/6/13
to d3...@googlegroups.com
Where do I put the json file? I have got geojson file called us-states.json I want to render it in my rails application using d3, how can I go about that ?

Phuoc Do

unread,
Nov 6, 2013, 1:34:39 PM11/6/13
to d3...@googlegroups.com
If you just need to serve static json file, you can put it in public/ folder. Then access it with:

$.get('/us-states.json', function(data) {
});

Phuoc

All files in Rails public/ folder will be accessible
Reply all
Reply to author
Forward
0 new messages