Search code examples
node.jsasync-awaitreadfilenode.js-fs

Substitute a Value in a Json file with value from another Json


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

{
    "label": "storage record",
    "data": [
        {
            "id": "8902uw",
            "type": "config",
            "values": {
                "access": "$access",
                "key": "$key"
            }
        },
        {
            "id": "90yueps",
            "type": "upload",
            "input": "localhost: `$path`"
}
 {
            "id": "9028901",
            "type": "change",
            "name": "Adjust data",
            "action": ""
        }

            ]
        }

values.json

{
    "key": "7c4afc",
    "access": "784030"
    }

index.js

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

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



(async () => {
  const config = await jsonReader("./values.json");

  const path = values.path;
  const access = values.access;
  const key = values.key;
  const bucketPath = bucketPath;


  const data = await jsonReader("./data.json");

  const fixedData = data.data?.map((o) => {
    if (o.type == "upload") return { ...o,  path };
    if (o.type == "config") return { ...o,  acsess, key };
   if (o.type == "change") return { ...o,  bucketPath };
    
  });
  await fs.writeFile("./data.json", JSON.stringify({ data: fixedData}, null, 3 ));
})();


Solution

  • 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