4

I am working with a Discord bot and have a JSON file called config.json that looks like this:

{
"token": "stuff"
"prefix": "!"
}

And I want to replace the "prefix: "!" line. My code is this:

if(cmd == "prefix"){
    var new_prefix = "\"prefix\": " + "\"" + String(args[0]) + "\"";
    var data = fs.readFileSync("config.json", "utf-8");
    var newValue = data.replace(/"prefix"\s*:\s*".+"/gm, "new_prefix");
    fs.writeFileSync("config.json", new_prefix, "utf-8");
};

Instead of only replacing the one line, it overwrites my entire config.JSON file so that after it looks like this:

"prefix":"stuffHere"

How can I make it only replace the one line and left the rest of the file intact?

1 Answer 1

4

Don't use regex for that, that makes things a whole lot more complicated than they need to be. Use JSON.parse to turn the JSON string into an object, assign to the prefix property on the object, and then write the stringified object:

if(cmd == "prefix"){
    var dataJSON = fs.readFileSync("config.json", "utf-8");
    var data = JSON.parse(dataJSON);
    data.prefix = "new_prefix";
    fs.writeFileSync("config.json", JSON.stringify(data), "utf-8");
}

If you had to use a regular expression for that, for whatever reason, then you would have to replace the "prefix": "<oldvalue>" with not only the new value, but with the prefix property as well. When matching the value (starts with "), lazy-repeat any character until you get to another ", if the string doesn't contain double quotes as well:

.replace(/"prefix": *".*?"/, '"prefix": "new prefix"')

https://regex101.com/r/zyhPqG/1

Sign up to request clarification or add additional context in comments.

2 Comments

So when I implement your solution, it changes prefix to "new_prefix" instead of what I assign it. I tried removing the quotes around it at data.prefix = new_prefix; and that did not work either.
Update: Actually it did work, I just had to remove the quotes and update var new_prefix = args[0]; Now my issue is getting the DIscord bot to update the prefix from the JSON file, maybe closing and reopening the file somehow.. but that is probably out of the scope of this question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.