skip to Main Content

I have this JSON in a File:

{
  "user1": {
    "id": 1,
    "nVote": 0,
    "comment": ""
  }
}

And I would like to add an object user2 with the same parameters and corresponding values.

function json2Array(json) {
  var result = [];
  var keys = Object.keys(json);
  keys.forEach(function (key) {
    result.push(json[key]);
  });
  return result;
}

const fs = require('fs');
const obj = JSON.parse(fs.readFileSync('./datei.json', 'utf8'));
const arObj = json2Array(obj);

let user = [];
user['user2'] = {
  "id": 2,
  "nVote": 1,
  "comment": 'test'
};

arObj.push(user);

that result:

    [
      { id: 1, nVote: 0, comment: '' },
      [ user2: { id: 2, nVote: 1, comment: 'test' } ]
    ]

But I would like to ultimately this result:

    {
      "user1": { id: 1, nVote: 0, comment: '' },
      "user2": { id: 2, nVote: 1, comment: 'test' }
    }

2

Answers


  1. If the result you want is an object, there’s no need to convert it to an array. Just add a property to the object.

    const obj = JSON.parse(fs.readFileSync('./datei.json', 'utf8'));
    obj['user2'] = {
      "id": 2,
      "nVote": 1,
      "comment": 'test'
    };
    
    Login or Signup to reply.
  2. all you have to do is to treat the json object as array

    simply

    consider this

    [
    {user1:{"id":2,"nVote":1,...}}
    {user2:{"id":2,"nVote":1,...}}
    ]
    

    so

    const obj = []
    obj.push({user1:{id:2,nVote:2})
    obj.push(({user2:{id:3,nVote:1})
    

    that’s all you need then you can store that using the fs to extract it to a json file

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search