Home >Web Front-end >JS Tutorial >How to read and write json files in nodejs? Method introduction

How to read and write json files in nodejs? Method introduction

青灯夜游
青灯夜游forward
2021-01-20 16:13:282391browse

How does nodejs read and write json files? The following article will introduce to you how to read and write json files in nodejs. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

How to read and write json files in nodejs? Method introduction

Related recommendations: "nodejs tutorial"

Reading json files

'use strict';

const fs = require('fs');

let rawdata = fs.readFileSync('student.json');
let student = JSON.parse(rawdata);
console.log(student);

写json文件:
'use strict';

const fs = require('fs');

let student = { 
    name: 'Mike',
    age: 23, 
    gender: 'Male',
    department: 'English',
    car: 'Honda' 
};
 
let data = JSON.stringify(student);
fs.writeFileSync('student-2.json', data);

Although this is what we want The data is written, but the data is in the form of a one-line string, which is difficult for us to read.
If you want the serialized JSON to be human readable, then change the JSON. Stringify function:
let data = JSON.stringify(student, null, 2);

json to csv

// require json-2-csv module
const converter = require('json-2-csv');
const fs = require('fs');

// read JSON from a file
const todos = JSON.parse(fs.readFileSync('todos.json'));

// convert JSON array to CSV string
(async () => {
    try {
        const csv = await converter.json2csvAsync(todos);

        // print CSV string
        console.log(csv);

        // write CSV to a file
        fs.writeFileSync('todos.csv', csv);

    } catch (err) {
        console.log(err);
    }
})();

csv to json

csv第一行为key,例如:  id,name,email,country,age
// require csvtojson module
const CSVToJSON = require('csvtojson');

// convert users.csv file to JSON array
(async () => {
    try {
        const users = await CSVToJSON().fromFile('users.csv');

        // log the JSON array
        console.log(users);

    } catch (err) {
        console.log(err);
    }
})();

More For programming-related knowledge, please visit: Introduction to Programming! !

The above is the detailed content of How to read and write json files in nodejs? Method introduction. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete