I try to import a local .json-file using d3.json()
.
The file filename.json
is stored in the same folder as my html file.
Yet the (json)-parameter is null.
d3.json("filename.json", function(json) {
root = json;
root.x0 = h / 2;
root.y0 = 0;});
. . .
}
My code is basically the same as in this d3.js example
If you're running in a browser, you cannot load local files.
But it's fairly easy to run a dev server, on the commandline, simply cd
into the directory with your files, then:
python -m SimpleHTTPServer
(or python -m http.server
using python 3)
Now in your browser, go to localhost:3000
(or :8000
or whatever is shown on the commandline).
The following used to work in older versions of d3:
var json = {"my": "json"};
d3.json(json, function(json) {
root = json;
root.x0 = h / 2;
root.y0 = 0;
});
Can you please explain your code a bit... how would I go from this
d3.json(filename, function(error, data) {...}
(Should I submit a separate question?)I would say outright that this answer's code is wrong, except for the 13 upvotes. d3.json takes a url as its first argument, not a json object. Ditto jQuery's $.get method. If the json is already defined in the file, there's no need to issue an ajax request via
d3.json
or$.get
; simply reference the variable directly. Or am I missing something here that would explain the 13 upvotes?@JamesConkling a variable isn't the same thing as a file. but yes, you can put the first line in my example in its own javascript file and that works as well.
@mb21 yeah, that's my point, if the json is defined in the script file, why use
d3.json
? If the json is not defined in the script file, then used3.json
and load the script via a server. Mixing the two approaches (defining the json in the script file and using d3.json makes no sense at all).@mb21, yes, in which case
d3.json()
takes a string representing the path to the file. In no case shouldd3.json()
take a JSON object (or anything other than a string) as its first argument. see here.