Home > front end >  converting JS objects to a json file
converting JS objects to a json file

Time:11-26

Does anyone know the best way to convert an array of objects that look like this,

 {
    date: '22 Nov 2022 18:49',
    ticker: 'RYAN',
    security: 'RYAN SPECIALTY HOLDINGS Inc ',
    rep: 'RYAN PATRICK G',
    relationship: 'Chief Executive Officer, 10%',
    transaction: 'Purchase ',
    shares: '81,375',
    price: '37.5016'
  },

into a JSON file in java script. Thanks

I have tries Using stringify, but with no success. ERRR:

TypeError: Converting circular structure to JSON
    --> starting at object with constructor 'Array'
    --- index 0 closes the circle
    at JSON.stringify (<anonymous>)
    at Object.<anonymous> (C:\Users\n\Desktop\New folder\index.js:99:22)
    at Module._compile (node:internal/modules/cjs/loader:1205:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1259:10)
    at Module.load (node:internal/modules/cjs/loader:1068:32)
    at Module._load (node:internal/modules/cjs/loader:909:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:82:12)
    at node:internal/main/run_main_module:23:47

CodePudding user response:

Here is an example of converting an array of objects to json and save it in a file using Node.js.

Here is the example:

const person = {
 name: 'John Doe',
 age: 35,
 usesStackoverflow: true
};

The object inside an array

const persons = [
 person,
 person,
 person
];

Converting object or array to JSON:

const jsonContent = JSON.stringify(persons); // you can also use person object to convert object to json

Saving it to a file:

const fs = require("fs");
const path = require("path");

const pathToSave = path.resolve("persons.json");
fs.writeFileSync(pathToSave, persons);

CodePudding user response:

Use can use spread syntax to "explode" all the elements of the array into a single new empty object by using Object.assign

const arrayOfPeople = [{},{},{}]

// Merge an array of objects into a single object
const objectOfPeople = Object.assign({}, ...arrayOfPeople);

The error use received is cover pretty well in Chrome sendrequest error: TypeError: Converting circular structure to JSON

  • Related