D3 lets us add graphics to a front-end web app easily.
Vue is a popular front end web framework.
They work great together. In this article, we’ll look at how to add graphics to a Vue app with D3.
Loading JSON
We can load JSON stored in an external file.
For example, we can write:
public/data.json
[
{
"name": "John",
"age": 30,
"city": "New York"
},
{
"name": "Jane",
"age": 20,
"city": "San Francisco"
}
]
src/App.js
import React, { useEffect } from "react";
import * as d3 from "d3";
const readJson = async () => {
const data = await d3.json("/data.json");
for (const { name, age } of data) {
console.log(name, age);
}
};
export default function App() {
useEffect(() => {
readJson();
}, []);
return <div className="App"></div>;
}
We have the readJson
function that reads data from data.json
.
And then we loop through the data
array that has the parsed entries.
We get:
John 30
Jane 20
logged.
Loading XML File
D3 also comes with the d3.xml
method to load the XML file.
For instance, we can write:
public/data.xml
<?xml version="1.0" encoding="UTF-8"?>
<root>
<row>
<name>John</name>
<age>30</age>
</row>
<row>
<name>Jane</name>
<age>32</age>
</row>
</root>
src/App.js
import React, { useEffect } from "react";
import * as d3 from "d3";
const readXml = async () => {
const data = await d3.xml("/data.xml");
for (const n of data.documentElement.getElementsByTagName("name")) {
console.log(n.textContent);
}
};
export default function App() {
useEffect(() => {
readXml();
}, []);
return <div className="App"></div>;
}
In the readXml
function, we call d3.xml
to read the data.
Then we get the elements with the name
tag and then loop through the returned items.
Loading Tab Separated Files
We can load tab-separated files with the d3.tsv
method.
For example, we can write:
public/data.tsv
name age city
John 30 New York
Jane 20 San Francisco
src/App.js
import React, { useEffect } from "react";
import * as d3 from "d3";
const readTsv = async () => {
const data = await d3.tsv("/data.tsv");
for (const { name, age, city } of data) {
console.log(name, age, city);
}
};
export default function App() {
useEffect(() => {
readTsv();
}, []);
return <div className="App"></div>;
}
We call the readTsv
method.
And then we loop through the parsed rows and log them.
Then we get:
John 30 New York
Jane 20 San Francisco
logged in the console.
Conclusion
We can load CSV, TSV, XML, and JSON files with D3 in our Vue app.