1

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.

2 Answers 2

9

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"
        }
    ]
}
Sign up to request clarification or add additional context in comments.

Comments

3

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


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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.