Skip to content
Advertisement

Key from one Json file to value of another Json file using node/Javascript

I tried and searched to make a JSON file who’s keys are data in other JSON file for eg:

admin in user.json is the key but it will act like value inside the Schema.json file same other keys which are present inside the user.json file will act like value inside Schema.json file.

suppose I have user.json name Json file and in user.json file my keys are admin, id, fname, lname, etc I want to make a another json with schema.json name where the keys which are present inside user.json are value of those schema.json

user.json

"addmin":{
  "id":"01",
  "fname":"tom",
  "lname":"jerry",
  "graduation":"PG",
  "address":"NYC",
  "job":"yes",
  "dreams":"travelling world"
  ...
  ...
  ...
}

image have a clear view what i want to achieve

enter image description here

I don’t know how this gonna be done I tried by doing this but still not happening am getting the value from the file if I get key I can store it in Schema.json

 fs.readFile(
    "user.json",
    function (err, data) {
      if (err) throw err;
      obj = JSON.parse(data);
      console.log(obj.admin.id);
    }
  );

Advertisement

Answer

I’m not sure you’ve defined the problem well enough yet, to be able to come up with a full solution. But it might involve using the the Object.keys() function (documented at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys) to help you parse your JSON object. To get you started, take a look at this:

fs.readFile(
    "user.json",
    function (err, data) {
      if (err) throw err;
      obj = JSON.parse(data);
      var schema = Object.keys(obj).map(function (key) {
          return {
              uid: key,
              schema: Object.keys(obj[key]).map(function (itemKey) {
                  return {
                      uid: itemKey
                  }
              }),
          };
      };
    }
  );
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement