Lewis Smith
Lewis Smith

Reputation: 37

Change specific JSON Value (C#)

Suppose I have a JSON file that looks like the following:

    [
  {
    "CheckName": "test2",
    "Times": [
      "0001-01-01T00:00:00",
      "2019-02-27T09:29:39.5654213"
    ]
  },
  {
    "CheckName": "test",
    "Times": [
      "0001-01-01T00:00:00",
      "2019-02-27T09:29:39.574397"
    ]
  }
]

Which I am looping over as below:

string Config = File.ReadAllText(@"C:\Scripts\Config.json");
dynamic ConfigFile = JsonConvert.DeserializeObject(Config);

foreach (var item in ConfigFile) {
    string CurrentCheck = item.CheckName;
    DateTime LastRun = item.Times[0];
    DateTime NextRun = item.Times[1];
    //Do stuff with the read values here
}

I need to update the first time value of test2, and then, later on, update it on test. However, there may be 50+ items in this JSON file, and I don't know where I am in the file, other than via a foreach loop (I'm reading the JSON, then looping over it to READ the values I need, but I need to write changes). Is it possible to update each specific value as I come across it, and then rewrite the JSON back to disk while retaining the other values as they are?

Alternatively, do I perhaps need to change how my JSON looks in order to make this task easier.

Upvotes: 0

Views: 163

Answers (1)

NibblyPig
NibblyPig

Reputation: 52932

You've deserialised your JSON into an object, in your case called ConfigFile.

You can make changes to the ConfigFile, which is a dynamic object, and then re-serialise to get your JSON string again.

You might find it easier to deserialise your JSON into objects, rather than iterating over them using dynamic, which helps especially in handling nested objects without your code becoming very messy.

The fact you don't know where you are in the loop doesn't matter, because objects, including nested ones, are reference types. This means although you've created something called item, it is still just a reference to the item so modifying it in one place modifies it in all places. If that makes sense.

Upvotes: 2

Related Questions