JSON replacing information with the same name

Asked

Viewed 46 times

1

I want to record two or more names in a JSON file. However, when I try to do this, it saves only the last information.

My job:

async function grava_login(){                          
 fs.writeFile("data.json", JSON.stringify({name: "Mohamed Almaci",
name:"Masq"}),"utf8", async function(err){    
 try{                                                    
  if(err){                                                
   console.log(err);                                     
  }                                                      
  else{                                                   
   console.log("The file was saved!");                   
  }                                                     
 }                                                      
 catch{                                                  
  console.log("Erro ao salvar dados no arquivo json!")
 }
})}

How I want JSON to stay:

{ 
  "name": "Mohamed almaci",
  "name": "Masq"
}

How the JSON is:

{
  "name":"Masq"
}
  • You are writing the name in making name="Masq". If you assign another key, for example name1: "Masq" , he will not write and then will be saved the whole object { 
 name: "Mohamed almaci",
 name1: "Masq"
} in the archive.

  • I realized that I am writing but I saw people doing it the way I want and working, I saw an example was with email, and the person managed to do the same thing I want, but it wasn’t with Ode and it was about another theme so I couldn’t figure out how to do it by Node js with lib Fs.

  • Look at this sample video https://youtu.be/iiADhChRriM minute 8:44 notice that he used name twice, but I can’t do this. I’ve tried every way.

1 answer

2


William,

To save a JSON with two properties name, you can create an array and each position of the array is an object that contains the property name and its value, example:

[
  {
    "name":"Mohamed Almaci"
  },
  {
    "name":"Masq"
  }
]

Including, in the video that you quoted (8:44), he follows this idea.


With that, your code would look like this:

const fs = require("fs");

async function grava_login() {
  fs.writeFile("data.json", JSON.stringify([{name: "Mohamed Almaci"},{name:"Masqx"}])
    , "utf8", async function(err) {
    if(err) {
      console.log(err);
    }
    else {
      console.log("The file was saved!");
    }
  });
}

grava_login();

See online: https://repl.it/repls/IvoryBruisedMachinecodeinstruction

  • :) had not used [ had tried with keys without creating the array, thanks.

  • I just don’t understand why his json file didn’t get [ and mine did, but it worked!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.