Marduk HS
Marduk HS

Reputation: 77

Create an array from csv for use with D3.js library

I have this cvs

<script id="cur_data" type="text/csv">Russian Federation,Italy,France,Luxembourg,Greece,Japan,Others
293,302,91,7,7,7,53</script>

how can I create the array format suitable for d3.js library ?

Upvotes: 0

Views: 161

Answers (2)

Yukul&#233;l&#233;
Yukul&#233;l&#233;

Reputation: 17062

CSV is not easy to parse (optional quotes, escaped char, separator not normalized (tab, comma, semicolon...)) you should use a library for that (d3 have one)

var csvSource = document.querySelector("#cur_data").textContent;
var data = d3.csv.parse(csvSource);

Upvotes: 1

zero298
zero298

Reputation: 26877

It would probably be better to keep it as a separate CSV file which you load asynchronously. So keep your data in data.csv and then load it using d3::csv() like so:

d3.csv("data.csv", function(data){
    console.log(data);
});

If you really want it in a <script> tag though, put it in an array or whatever data structure is appropriate.

<script>
    var data = [
        {
            country: "Russian Federation",
            value: 293
        },
        {
            country: "Italy",
            value: 302
        },
        {
            country: "France",
            value: 91
        },
        {
            country: "Luxembourg",
            value: 7
        },
        {
            country: "Greece",
            value: 7
        },
        {
            country: "Japan"
            value: 7
        },
        {
            country: "Others",
            value: 53
        }
    ];
</script>

Then use the data in whatever function d3.js has. You don't typically make <script> tags with type="text/csv". You would use text/javascript if anything since it's primarily only used for JavaScript. See MDN script tag documentation

Upvotes: 1

Related Questions