I have a settings.json file present in the Release folder of my application. What I want to do is change the value of it, not temporarily, permanently.. That means, deleting the old entry, writing a new one and saving it.
Here is the format of the JSON file
{ "Admins":["234567"], "ApiKey":"Text", "mainLog": "syslog.log", "UseSeparateProcesses": "false", "AutoStartAllBots": "true", "Bots": [ { "Username":"BOT USERNAME", "Password":"BOT PASSWORD", "DisplayName":"TestBot", "Backpack":"", "ChatResponse":"Hi there bro", "logFile": "TestBot.log", "BotControlClass": "Text", "MaximumTradeTime":180, "MaximumActionGap":30, "DisplayNamePrefix":"[AutomatedBot] ", "TradePollingInterval":800, "LogLevel":"Success", "AutoStart": "true" } ] }
Suppose I want to change the password value and instead of BOT PASSWORD I want it to be only password. How do I do that?
Procedure. In the Enterprise Explorer view, right-click your . json file or other file type that contains JSON code and select Open With > JSON Editor. You can compress JSON strings so that the strings display on one line with white space removed between JSON elements.
JSON is a plain text file that can be opened in a text editor. You can easily modify and save it back without any special software.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With