DataFrame.toJSON
Convert DataFrame to JSON format
Deprecated in v1.1.0: Use the dfd.toJSON function directly instead
DataFrame.toJSON(options)
Parameters
Type
Description
Default
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 toJSON 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
const dfd = require("danfojs-node")
let data = {
Abs: [20.2, 30, 47.3],
Count: [34, 4, 5],
"country code": ["NG", "FR", "GH"],
};
let df = new dfd.DataFrame(data);
const jsonObj = df.toJSON(); //defaults to column format
console.log(jsonObj);
//output
[
{ Abs: 20.2, Count: 34, 'country code': 'NG' },
{ Abs: 30, Count: 4, 'country code': 'FR' },
{ Abs: 47.3, Count: 5, 'country code': 'GH' }
]
//row format
const jsonObjRow = df.toJSON({
format: "row"
});
console.log(jsonObjRow);
//output
{
Abs: [ 20.2, 30, 47.3 ],
Count: [ 34, 4, 5 ],
'country code': [ 'NG', 'FR', 'GH' ]
}
Convert DataFrame/Series to JSON and write to local file path
Writing a DataFrame/Series as JSON, to a local file path is only supported in the Nodejs environment
const dfd = require("danfojs-node")
let data = {
Abs: [20.2, 30, 47.3],
Count: [34, 4, 5],
"country code": ["NG", "FR", "GH"],
};
let df = new dfd.DataFrame(data);
df.toJSON({ filePath: "./testOutput.json" });
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.
let data = {
Abs: [20.2, 30, 47.3],
Count: [34, 4, 5],
"country code": ["NG", "FR", "GH"],
};
let df = new dfd.DataFrame(data);
df.toJSON({ fileName: "test_out.json", download: true });
Last updated
Was this helpful?