Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change values in JSON file (writing files)

Tags:

json

c#

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?

like image 951
Bone Avatar asked Feb 11 '14 06:02

Bone


People also ask

How do I change data in a JSON file?

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.

Can you edit a JSON file?

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.


1 Answers

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.

like image 125
agentnega Avatar answered Sep 18 '22 12:09

agentnega