How do i create a JSON file from an array in JavaScript?

Benji :

I'm working on a Node.js project using JavaScript. My issue is that I have an array with some data, and i want to use this data in the array to create a JSON file.

This is what I have:

var cars = ["Saab", "Volvo", "BMW"];

This is what I want:

{
  "cars": [
    {
       "mark" : "Saab"
    },
    {
       "mark" : "Volvo"
    },
    {
       "mark" : "BMW"
    }
  ]
}

Java has a library called Jackson which helps with this. Does Node.js not have something similar?

Please if the question does not live up to the rules, let me know.

Terry Lennox :

This is very simple indeed in Node.js, you can use the JSON methods stringify and parse to create strings from objects and arrays. We can first use reduce to create a car object from the car array.

I'm using JSON.stringify() with null, 4 as the last arguments to pretty-print to the file. If we wanted to print everything to one line, we'd just use JSON.stringify(carObj).

For example:

const fs = require("fs");

const cars =  ["Saab", "Volvo", "BMW"];
const carObj =  cars.reduce((map, car) => { 
    map.cars.push( { mark: car} );
    return map;
}, { cars: []})

// Write cars object to file..
fs.writeFileSync("./cars.json", JSON.stringify(carObj, null, 4));

// Read back from the file...
const carsFromFile = JSON.parse(fs.readFileSync("./cars.json", "utf8"));
console.log("Cars from file:", carsFromFile);

The cars.json file will look like so:

{
    "cars": [
        {
            "mark": "Saab"
        },
        {
            "mark": "Volvo"
        },
        {
            "mark": "BMW"
        }
    ]
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=220764&siteId=1