简体   繁体   中英

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

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.

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"
        }
    ]
}

 var cars = ["Saab", "Volvo", "BMW"]; const result = cars.reduce((acc, x) => { acc.cars.push({ mark: x }) return acc; }, { cars: [] }) console.log(result)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM