问题
I need to populate a 2d array, e.g.,
var dataset = [[1,3,3,5,6,7],[3,5,8,3,2,6],[9,0,6,3,6,3],[3,4,4,5,6,8],[3,4,5,2,1,8]];
Where the information comes from external sources, while I have the control in the format to store them (csv,json etc., to be read by functions like d3.csv, d3.json etc.).
What are the simplest ways to store 2d array in external files, and to read in to populate the variable like dataset when doing d3 processing?
回答1:
You can do it using a CSV file, a TSV file, a XML file, a text file... However, I believe that the simplest way to store your array of arrays is just saving it (the way it is right now, no change, but without the semicolon of course) in a JSON file.
Therefore, if you ask what is the simplest way (and, if by simplest, you mean the way which requires less code to get the final result), JSON is by far the best choice.
Here is a plunker illustrating this (I can't use stack snippets to load JSON files), have a look at the console: https://plnkr.co/edit/2ksVXhnP8EFFHo8P1vrt?p=preview
The code is simply:
d3.json("data.json", function(data){
console.log(data)
})
And the data.json file is just:
[
[1, 3, 3, 5, 6, 7],
[3, 5, 8, 3, 2, 6],
[9, 0, 6, 3, 6, 3],
[3, 4, 4, 5, 6, 8],
[3, 4, 5, 2, 1, 8]
]
回答2:
I guess it really depends on what "best way" means. D3 offers a variety of ways to load in data: csv, tsv, json. Since many APIs return JSON data these days, I like to stick to that format if I can. Should you choose to go that way, you can use the following D3 function:
d3.json("path/to/file.json", function(dataset) {
// Data is now in dataset
console.log(dataset);
});
But of course you can do the exact same thing with csv or tsv.
来源:https://stackoverflow.com/questions/46632435/simplest-way-to-store-2d-array-in-external-file