Home > Software engineering >  Creating a nested Json from an array
Creating a nested Json from an array

Time:03-28

I have this Js array:

[0][
    "Paris ",
    "75000",
]
[1][
    "Toulouse ",
    "31000",
]
[2][
    "Marseille ",
    "13000",
]

How to convert this array to Json?

{
  "city": "Paris",
  "zip": "75000"
},
{
  "city": "Toulouse",
  "zip": "31000"
},
{
  "city": "Marseille",
  "zip": "13000"
}

I tried with the JSON.stringify() function but I don't get the expected result.

Thanks

CodePudding user response:

Youre array declaration isn't correct. This is the correct syntax for declaring an array in JS and using JSON.stringify on it:

tab = [
  {city: 'Paris', zip: '75000'},
  {city: 'Toulouse', zip: '31000'},
  {city: 'Marseille', zip: '13000'}
];

JSON.stringify(tab, null, 2)

CodePudding user response:

Let's assume there is an array named codes whose entries are sub-arrays holding city name and zip code strings. Let's also assume that the structure of codes is not something you can change.

The following example is on way of converting it into an array of objects with city and zip properties:

const codes = [
  ["Paris ","75000"],
  ["Toulouse", "31000"],
  ["Marseille ","13000"],
];
   
let jsonText = JSON.stringify( 
   codes.map(entry=>( 
      {city:entry[0], zip:entry[1]}
   )),
   null,
   2
);

console.log(jsonText);  

A variation of the map argument function could use Destructuring assignment to make the code easier to read at a glance:

 codes.map(entry=>{
     const [city, zip] = entry;
     return {city,zip};
 })

Of course there are other coding techniques which could convert an arrays of arrays into arrays of objects, the choice of which one to use is up to you.

  • Related