Change values in JSON file (writing files)

Here’s a simple & cheap way to do it (assuming .NET 4.0 and up):

string json = File.ReadAllText("settings.json");
dynamic jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
jsonObj["Bots"][0]["Password"] = "new password";
string output = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj, Newtonsoft.Json.Formatting.Indented);
File.WriteAllText("settings.json", output);

The use of dynamic lets you index right into json objects and arrays very simply. However, you do lose out on compile-time checking. For quick-and-dirty it’s really nice but for production code you’d probably want the fully fleshed-out classes as per @gitesh.tyagi’s solution.

Leave a Comment