Fetch d3.js array from a url

≡放荡痞女 提交于 2019-12-13 06:09:47

问题


This is the kind of data that I have

{ "_id" : ObjectId("kdahfa"), "minTime" : ISODate("2016-04-02T00:00:00.000+0000"), "maxTime" : ISODate("2016-04-02T00:11:00.000+0000"), "Time" : 660.0, "Name" : "Sam" }   
{ "_id" : ObjectId("aabhk"), "minTime" : ISODate("2016-04-02T01:00:00.000+0000"), "maxTime" : ISODate("2016-04-02T02:14:25.000+0000"), "Time" : 4465.0, "Name" : "Bob" }  
{ "_id" : ObjectId("bak"), "minTime" : ISODate("2016-04-02T19:00:00.000+0000"),     "maxTime" : ISODate("2016-04-02T19:52:22.000+0000"), "Time" : 3142.0, "Name" :     "Sam" }  

I wrote a python(bottle) code to fetch the data from mongoDB server and run it on local host. The url is http://localhost:8080/result.

  @bottle.route('/result')
     def grab_record():
     bottle.response.headers['Access-Control-Allow-Origin'] = '*'
     a = dbcoll.find_one({},{'_id':False})
     a['minTime'] = str(a['minTime'])
     a['maxTime'] = str(a['maxTime'])
     response.content_type = 'application/json'  
     return dumps(a)

Now I wish to create a d3.js graph from this taking help from http://bl.ocks.org/dk8996/5449641. I want the task array in the example.js to take data from the url/mongodb. What changes should I make to my d3.js code to make it function according to my requirements?

d3.json("http://localhost:8080/result", function(error, data) {
data.forEach(function(d) {
    d.maxTime = parseDate(d.maxTime);
    d.minTime = parseDate(d.minTime);
    d.Time = +d.Time;
});

var taskNames = ["Bob", "Sam"];

taskStatus = {
"Bob": "bar",
"Sam": "bar-failed",
};

var gantt = d3.gantt().taskTypes(taskNames).taskStatus(taskStatus);
gantt(tasks);
});

These are the changes in the example.js file that I've made so far. I am getting an error
Uncaught TypeError: data.forEach is not a function
I wish to create an array of the returned d3.js objects and use it like it is used on http://bl.ocks.org/dk8996/5449641.


回答1:


 a = dbcoll.find_one({},{'_id':False})

In this line, you are only querying for one entry in your database, that is why the result returned is a single object instead of an array (probably you also need to change the first parameter {} to [] or something to denote array but I am not familiar with dbcoll.

You need to change find_one into find or something, and you will get an array.

Then the post-processing, you needs to iterate through the array of a:

a = a.map(function(b){
     b['minTime'] = str(b['minTime'])
     b['maxTime'] = str(b['maxTime'])
     return b;
}

In MongoDB there is a method find: https://docs.mongodb.com/manual/reference/method/db.collection.find/



来源:https://stackoverflow.com/questions/37517727/fetch-d3-js-array-from-a-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!