Home > Mobile >  How to replace specific parts of a json file using node.js
How to replace specific parts of a json file using node.js

Time:10-20

Currently, I have a JSON file that looks like this:

"1E10BC5D4EC68EE2916BFD97F23E951C": "Seattle Seahawks",
"E6B87019417436B73B62F7802763A289": "Seaside style. ",
"81EEA9E6400BFEADE161559AF14EE468": " {1}",
"6F02148E4A78B33C1CEB75BC2753CA69": " {EndDate}",
"D89CA2634FFF8FA02D028096BAAE6963": "\"You have received a reward for completing the {Bundle Name} {Number} challenges!",
"Mission": {
    "Default Mission Info Description": "Default Mission Description",
    "Default Mission Info Name": "Default Mission Name",
    "RewardDescription": "You ranked {PositionRank}. For your efforts, you have been awarded:",
    "NonParticipationRewardDescription": "Your teammates did a great job! For their efforts, you have been awarded:",
    "RewardTitle": "{MissionName} Completed!"
  }

It goes on for about 40,000 lines, and I would like to modify all of the strings set by it. Currently, I am using @zuzak/owo to try to accomplish this. My current code looks like this:

const owo = require('@zuzak/owo')
fs = require('fs');

var name = '../jsonfile.json';

var data = fs.readFileSync(name).toString();


fs.writeFileSync('../owo.json', JSON.stringify(owo(data)))

How would I be able to only change the strings, such as "Seaside style. " and not edit any of the string names, such as "81EEA9E6400BFEADE161559AF14EE468" (sorry for any incorrect wording, hopefully you can understand what I am saying.)

In case you need it, here is the main code used in @zuzak/owo:

const addAffixes = (str) => randomItem(prefixes)   str   randomItem(suffixes)
const substitute = (str) => {
  const replacements = Object.keys(substitutions)
  replacements.forEach((x) => {
    str = replaceString(str, x, substitutions[x])
  })
  return str
}

CodePudding user response:

Parse the JSON, iterate over keys, modify values. If necessary recursively iterate over subobjects too:

function owoifyObject (obj) {
  for (const key in obj) {
    if (typeof obj[key] === 'string') {
      obj[key] = owo(obj[key])
    } else if (typeof obj[key] === 'object' && obj[key]) {
      owoifyObject(obj[key])
    }
  }
}

const data = JSON.parse(fs.readFileSync('file.json').toString())
owoifyObject(data)
fs.writeFileSync('file2.json', JSON.stringify(data, null, 4))

Note that the argument 4 in JSON.stringify is purely there for formatting so that the result looks something like your input did, otherwise you'd get all the data in a single line.

CodePudding user response:

Use JSON.parse() to parse the JSON file into an object. Then go through the object calling owo() on each value.

var data = JSON.parse(fs.readFileSync(name).toString());
for (let key in data) {
    data[key] = owo(data[key]);
}
fs.writeFileSync("../owo.json", JSON.stringify(data));
  • Related