Home > Enterprise >  Substitute a Value in a Json file with value from another Json
Substitute a Value in a Json file with value from another Json

Time:12-12

I have two JSON files data.json and values.json. I want to read whatever the values of aws and bucket in values.json are, and use them in data.json. How can I achieve this with node js?

I have written a function that reads the content of the values.json file and stores them in a variable, but I am confused about how to write them to data.json as values of "aws": " " and "bucket": " ".

In cases where aws and bucket already have values, I want those existing values to be replaced by whatever was read from data.json. How can I implement this?

data.json

{
    "data": [
   
    {
        "id": "78403839403",
        "type": "storage",
        "name": "List of students"
    },
    {
        "id": "8987030473920",
        "type": "storage",
        "aws": "",
        "bucket": ""
    }
]
}

values.json

{
    "aws": "7c4afc",
    "bucket": "studentsRecord"
    }

index.js

const fs = require('fs')

function jsonReader(filePath, values) {
    fs.readFile(filePath, (err, fileData) => {
      if (err) {
        return values && values(err);
      }
      try {
        const object = JSON.parse(fileData);
        return values && values(null, object);
      } catch (err) {
        return values && values(err);
      }
    });
  }

  jsonReader("./values.json", (err, credentials) => {
    if (err) {
      console.log(err);
      return;
    }
    const aws = credentials.aws
    const bucket = credentials.bucket
    console.log(aws, bucket); 
  });

CodePudding user response:

First you need to change the current json and finally you need to write the modified json into you data.json again. I would recommend to you to use async/await instead of use promise then directly. I rewrite your code with async/await structure, but you can adapt if you prefer to use callback instead. Follow the example code:

const fs = require("fs").promises;

async function jsonReader(filePath, values) {
  const data = await fs.readFile(filePath);
  try {
    return JSON.parse(data);
  } catch (err) {
    console.log(err);
  }
}

(async () => {
  const credentials = await jsonReader("./values.json");
  const aws = credentials.aws;
  const bucket = credentials.bucket;
  const data = await jsonReader("./data.json");

  const fixedData = data.data?.map((o) => {
    if (o.type == "storage") return { ...o, aws, bucket };
  });
  await fs.writeFile("./data.json", JSON.stringify({ data: fixedData }));
})();

Edit: I put with .map instead of .foreach to avoid mutable the array as mentioned by @JSmart523

  • Related