danfo.to_json
danfo.to_json(data, options) [source]
Text
Text
Text
Text
Parameters
Type
Description
Default
data
Series or DataFrame
The Series or DataFrame to write to CSV
options
object, optional
Configuration object:
{
filePath: Local file path to write the CSV file to. If not specified, the CSV will be returned as a string. Only needed in Nodejs version fileName: The name of the file to download as. Only needed in browser environment. format: The format of the JSON. Can be one of row or column.
}
{ format: "column" }
The to_json function can be used to write out a DataFrame or Series to JSON format/file. The output is configurable and will depend on the environment. In the following examples, we show you how to write/download a JSON file from Node and Browser environments.

Convert DataFrame/Series to JSON and return value

Node.js
Browser
1
const dfd = require("danfojs-node")
2
3
let data = {
4
Abs: [20.2, 30, 47.3],
5
Count: [34, 4, 5],
6
"country code": ["NG", "FR", "GH"],
7
};
8
9
let df = new dfd.DataFrame(data);
10
11
const jsonObj = dfd.to_json(df, { download: false }); //column format
12
console.log(jsonObj);
13
14
//output
15
[
16
{ Abs: 20.2, Count: 34, 'country code': 'NG' },
17
{ Abs: 30, Count: 4, 'country code': 'FR' },
18
{ Abs: 47.3, Count: 5, 'country code': 'GH' }
19
]
20
21
//row format
22
const jsonObj = dfd.to_json(df, {
23
download: false,
24
format: "row"
25
});
26
27
console.log(jsonObj);
28
//output
29
{
30
Abs: [ 20.2, 30, 47.3 ],
31
Count: [ 34, 4, 5 ],
32
'country code': [ 'NG', 'FR', 'GH' ]
33
}
Copied!
1
<!DOCTYPE html>
2
<html lang="en">
3
4
<head>
5
<meta charset="UTF-8">
6
<meta name="viewport" content="width=device-width, initial-scale=1.0">
7
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lib/bundle.min.js"></script>
8
<title>Document</title>
9
</head>
10
11
<body>
12
13
<script>
14
15
let data = {
16
Abs: [20.2, 30, 47.3],
17
Count: [34, 4, 5],
18
"country code": ["NG", "FR", "GH"],
19
};
20
21
let df = new dfd.DataFrame(data);
22
23
const csv = df.to_csv({ download: false });
24
console.log(csv);
25
</script>
26
</body>
27
28
</html>
Copied!

Convert DataFrame/Series to JSON and write to file path

Writing a DataFrame/Series as JSON, to a local file path is only supported in the Nodejs environment
Node.js
1
const dfd = require("danfojs-node")
2
3
let data = {
4
Abs: [20.2, 30, 47.3],
5
Count: [34, 4, 5],
6
"country code": ["NG", "FR", "GH"],
7
};
8
9
let df = new dfd.DataFrame(data);
10
11
dfd.to_json(df, { filePath: "./testOutput.json" });
Copied!

Convert DataFrame/Series to JSON and download file in browser

You can automatically convert and download a DataFrame/Series as a JSON file in a browser environment, by specifying a fileName and setting download to true.
1
let data = {
2
Abs: [20.2, 30, 47.3],
3
Count: [34, 4, 5],
4
"country code": ["NG", "FR", "GH"],
5
};
6
7
let df = new dfd.DataFrame(data);
8
9
dfd.to_json(df, { fileName: "test_out.json" });
Copied!
Last modified 17d ago