I'm creating a D3 bubble chart, using json data. I'm using sinatra for my app, and my json data is available at localhost:4567/data.json
I tried using
var myData = [];
$.get('data.json', function(data) {
myData = data;
console.log(myData);
.......
and I get the correct values in the javascript console, but the bubble chart does not render. (The rest of the code works if I copy and paste the data from 'data.json' and set it to a var, but it does not work if I use the $get method).
Do you have any ideas on how I could access this json data from localhost:4567?
Much appreciated,
Tim
I think what is probably going on is that jquery isn't automatically parsing the data as a JSON object due to missing MIME headers in the response from your server. Try using getJSON instead.
you can simply use
d3.json('data.json', function(data) {
myData = data;
console.log(myData);
.......
to read the json file
Related
i'm using Tabulator to Mange some tables and i've see how to download the file in JSON format and others but i wonder if there's a function included to save data in JSON object instead so I can upload it directly to the server
i've checked this page http://tabulator.info/docs/4.1/download and i got the idea to use "Custom File Formatter" then intercept the download bolb but i keep getting an error referring to
setFileContents(names.join(", "), "text/plain");
Uncaught ReferenceError: setFileContents is not defined
function code:
document.querySelector("#uploadJSON").onclick = function(){
var fileFormatter = function(columns, data, options){
var names = [];
data.forEach(function(row){
names.push(row.name);
});
setFileContents(names.join(", "), "text/plain");
}
table.download(fileFormatter, "test.json");
}
You can use the getData function to get an array of row data objects:
var data = table.getData();
And then JSON encode it with the stringify function:
var jsonData = JSON.stringify(data);
It is then down to you to choose how to upload it to the server, in-fact several ajax libraries will even do the JSON encoding for you so you would just need to pass them the results from the getData function
I'm just having a little trouble understanding the documentation for CSV Parse with D3. I currently have:
d3.parse("data.csv",function(data){
salesData = data;
});
But I keep on getting the error:
Uncaught TypeError: d3.parse is not a function
What is this supposed to look like? I'm just a little confused, and the only examples that I could find was something like this.
I also tried something like:
d3.dsv.parse("data.csv",function(data){
salesData = data;
});
and got:
Uncaught TypeError: Cannot read property 'parse' of undefined
Why is this happening? Any help would be greatly appreaciated, thanks!!
There is some misunderstanding here: you're confusing d3.csv, which is a request, with d3.csvParse, which parses a string (and also mixing D3 v3 syntax with D3 v4 syntax). This is the difference:
d3.csv (D3 v4)
The d3.csv function, which takes as arguments (url[[, row], callback]):
Returns a new request for the CSV file at the specified url with the default mime type text/csv. (emphasis mine)
So, as you can see, you use d3.csv when you want to request a given CSV file at a given url.
For example, the snippet below gets the CSV at the url between quotes, which looks like this...
name, parent
Level 2: A, Top Level
Top Level, null
Son of A, Level 2: A
Daughter of A, Level 2: A
Level 2: B, Top Level
... and logs the parsed CSV file, check it:
d3.csv("https://gist.githubusercontent.com/d3noob/fa0f16e271cb191ae85f/raw/bf896176236341f56a55b36c8fc40e32c73051ad/treedata.csv", function(data){
console.log(data);
});
<script src="https://d3js.org/d3.v4.min.js"></script>
d3.csvParse
On the other hand, d3.csvParse (or d3.csv.parse in D3 v3), which takes as arguments (string[, row]):
Parses the specified string, which must be in the delimiter-separated values format with the appropriate delimiter, returning an array of objects representing the parsed rows.
So, you use d3.csvParse when you want to parse a string.
Here is a demo, suppose you have this string:
var data = "foo,bar,baz\n42,33,42\n12,76,54\n13,42,17";
If you want to parse it, you'll use d3.csvParse, not d3.csv:
var data = "foo,bar,baz\n42,33,42\n12,76,54\n13,42,17";
var parsed = d3.csvParse(data);
console.log(parsed);
<script src="https://d3js.org/d3.v4.min.js"></script>
You can get csv data into d3 like the following -
// get the data
d3.csv("data.csv", function(error, data) {
if (error) throw error;
console.log(data);
//format data if required...
//draw chart
});
I also could not get the d3.csv("csv_file.csv", function(data) { //modifying code }
to work.
A classmate recommended using the following, which has worked so far:
d3.csv("data.csv").then(function(data){
//modifying code
}
As noted in the comments below, this is a fix if you're running v5 instead of v4.
Use d3.csv("data.csv", function(data){...}) to get CSV from url and parse, or use d3.csv.parse() to parse a CSV-formatted string.
Here is the code you can use to read csv file using d3.js
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
d3.csv("csv/cars.csv", function(data) {
console.log(data[0]);
});
</script>
Note that, the csv file name is "cars.csv", and the file is saved in a folder called csv.
console.log(data[0])
will help you to see the data output in the browser debug window. Where, you can also find if there is any error as well.
I have json file with given data (total.json)
var data = {"trololo":{"info":"61511","path".... }}
I need to get object "info" and then print data "61511" in alert window
I include my json like
var FILE = 'total'
var data_file_names = {};
data_file_names[FILE] = 'total.json';
And then i use it like
var data_trololo = data_file_names[FILE];
Plese, help me print object "info". Maybe there is another way to solve this problem
You need to make an ajax call to the json file. Then you can access the array like the below example.
Note : Your json wasn't properly formatted.
var data = {
"trololo":{
"info": ["61511","path"]
}
};
console.log(data.trololo.info[0]); //this one will print 61511
Usually one can make an ajax call to read the file on the server.
But if you are ok with using HTML5 features then go through the link find out how to read the file on the browser itself. Though File API being part of HTML5 spec is stable across browsers.
http://www.html5rocks.com/en/tutorials/file/dndfiles/
I'm new to JSON/AJAX and
I've some problems with displaying data out of a JSON-object I've got from a server..
The url "http://localhost:8387/rest/resourcestatus.json" represents this object, which I would like to display via HTML/Javascript.. This object stores some monitoring information:
{"groupStatus":[
{"id":"AL Process","time":1332755316976,"level":0,"warningIds":[],"errorIds":[]},
{"id":"AL:instance1","time":1332919465317,"level":0,"warningIds":[],"errorIds":[]},
{"id":"AL:instance2","time":1332919465317,"level":1,"warningIds":["documentarea.locked"],"errorIds":[]},
{"id":"SL","time":1331208543687,"level":0,"warningIds":[],"errorIds":[]}
]}
Since the requested url is different from my domain I can't create a typical XMLHttpRequest.. So I found out that there's an AJAX cross-domain request which can be realised via jQuerys "getJSON()" method.
I want to display the ids and their level in a table.
Any solution to achieve this?
i think you are referring to JSONP. see jQuery.ajax Ex:
var url = 'http://localhost:8387/rest/resourcestatus.json';
$.getJSON(url+'?callback=?', function(data)
{
//data is
/*{
"groupStatus":
[
{"id":"AL Process","time":1332755316976,"level":0,"warningIds":[],"errorIds":[]},
{"id":"AL:instance1","time":1332919465317,"level":0,"warningIds":[],"errorIds":[]},
{"id":"AL:instance2","time":1332919465317,"level":1,"warningIds":["documentarea.locked"],"errorIds":[]},
{"id":"SL","time":1331208543687,"level":0,"warningIds":[],"errorIds":[]}
]
}*/
});
on the server side you will need to wrap the response into a JavaScript function: response = Request["callback"] +"("+ response+")";
the result will look like this:
?({"groupStatus":[{"id":"AL ....})
So the browser will actually load a valid java script code.
The callback function of $.getJSON contains the result of the AJAX call in it's argument.
$.getJSON('http://localhost:8387/rest/resourcestatus.json', function(data) {
$(data.groupStatus).each(function() {
// do something with $(this).id
});
});
I am trying to create some JSON to be used for displaying a chart using Highcharts
http://www.highcharts.com/
I have copied one of their examples:
http://www.highcharts.com/stock/demo/basic-line
Click "View Options" under the graph to see the source. There is also a JSFiddle there to play with
If I copy that locally it all works fine.
The problem is when I try to use my own data source.
I have an ASP.Net MVC controler which is spitting out a list of arrays, just like their data source. However, that doesn't work.
Their datasource looks like this
http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=?
and they retrieve it like this
$.getJSON('http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=?', function (data) {
So I thought I'd take a step back and copy thier data exactly and put it in a text file on my server and try that:
So I tried this
$.getJSON('/data.txt', function (data) {
and this
$.get('/data.txt', function (data) {
but neither work
I have also tried using both JSON.parse and jQuery.parseJSON after retrieving the data, but again - that doesn't seem to work
I am also wondering what the ? is at the start of their data
Their data looks like this
?([[<some data>],[some data]]);
I don't get any error message, the graph just doesn't display
any ideas?
SOLVED IT
Just need to retrive the data and turn it into an array and pass it to the chart.
Needs to be an array, not JSON
That datasource is ouputting JSONP, which is for cross-domain AJAX requests. It's not valid 'raw' JSON because of that extra callback(...) wrapper.
Read up about it here: http://api.jquery.com/jQuery.ajax/ under the 'dataType' section.
As you say in your tags, it's not JSON, it's JSONP. Do not parse it, catch it with a callback. Use jQuery.getScript to do it, and define function callback(data). Inside that function, data should contain the (parsed) object. Also, replace the ? in the URL with callback (or whatever you named your function) - ? is not a valid identifier in JavaScript, so ?([....]) is nonsense.