Max Rheault
Max Rheault

Reputation: 27

Modify a json file

I want to modify my json file without losing the the other string and value

const fs = require('fs');
var logPath = 'log.json'
var logRead = fs.readFileSync(logPath)
var logFile = JSON.parse(logRead)



LogChannel = '2'
Server = 'Number2'
User = 300


if (!logFile[Server]){
    
    logFile[Server] = {'LogChannelId': LogChannel ,'NumberOfUser':User }
    fs.writeFileSync(logPath, JSON.stringify(logFile, null, 2));
  }
else {

    logFile[Server] = {'NumberOfUser':User+1}
    fs.writeFileSync(logPath, JSON.stringify(logFile, null, 2));

}

When json object is created I have the two String with the value

{
  "Number1": {
    "LogChannelId": "2",
    "NumberOfUser": 300
  },
  "Number2": {
    "LogChannelId": "2",
    "NumberOfUser": 300
  }
}

After modify my json file I lost LogChannelId string

{
  "Number1": {
    "LogChannelId": "2",
    "NumberOfUser": 300
  },
  "Number2": {
    "NumberOfUser": 301
  }
}

How can I keep my LogChannelId string and be able to modify only NumberOfUser

Upvotes: 0

Views: 214

Answers (1)

Dominik
Dominik

Reputation: 6313

Instead of overriding the entire object you can just assign a new value to one of its keys.

const fs = require('fs');
var logPath = 'log.json'
var logRead = fs.readFileSync(logPath)
var logFile = JSON.parse(logRead)

var LogChannel = '2'
var Server = 'Number2'
var User = 300


if (!logFile[Server]){
    logFile[Server] = {'LogChannelId': LogChannel ,'NumberOfUser':User }
    fs.writeFileSync(logPath, JSON.stringify(logFile, null, 2));
  }
else {
    logFile[Server].NumberOfUser = User+1;
// CHANGE --------------^
    fs.writeFileSync(logPath, JSON.stringify(logFile, null, 2));
}

Upvotes: 1

Related Questions