0

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 ?

2 Answers 2

1

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

1

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);
0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.