0

My file contains below JSON structure.

{
"Name":"M",
"Age":"2",
"Bots":[{
   "from":"D/2334/23",
   "To":"02-04-2023"
},{
   "from":"E/2s/1",
   "To":"03-04-2023"
},{
   "from":"ESS/5sB/DS",
   "To":"03-04-2023"
}

]
}

Here i would like to change the "To" value in each jarray objects to get from "from" on each row.

Bots:[
{
"from":"D/2334/23",
"To":"2334/23"
},
{
"from":"E/2s/1",
"To":"2s/1"
},
{
"from:"ESS/5sB/DS",
"To":"5sB/DS"
}
]

I referred to this [https://stackoverflow.com/questions/21695185/change-values-in-json-file-writing-files] but I am unable to update that file into the same json, and it failed to read the "from value" using Split('/')[1]

string json = File.ReadAllText("settings.json");
dynamic jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
jsonObj["Bots"][0]["To"] = jsonObj["Bots"][0]["from"].split('/')[1];

[1]:

Anyone suggest a way to get the "from" value using split('/') or any other functions?

Mister X
  • 3,406
  • 3
  • 31
  • 72

2 Answers2

1

No need to use dynamic, use API provided by the library to process the dynamic JSON (JObject, JToken, JArray, see LINQ to JSON docs for some examples):

var jsonObj = JsonConvert.DeserializeObject<JObject>(json); // or JObject.Parse
foreach (var jToken in jsonObj["Bots"])
{
    jToken["To"] = jToken["from"].Value<string>().Split('/')[1]; // TODO - validate that token is of correct type and have enough elements after split
}

Console.WriteLine(JsonConvert.SerializeObject(jsonObj));
// Prints:
// {"Name":"M","Age":"2","Bots":[{"from":"D/2334/23","To":"2334"},{"from":"E/2s/1","To":"2s"},{"from":"ESS/5sB/DS","To":"5sB"}]}

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
1

try substring instead of split

    var jObj = JObject.Parse(json);

    foreach (var item in jObj["Bots"])
        item["To"] = ((string)item["from"])
                         .Substring(((string)item["from"]).IndexOf("/") + 1);

    json = jObj.ToString(); // or "{ \"Bots\": " + jObj["Bots"].ToString() + " }";

    Console.WriteLine(json);

    //or 
    File.WriteAllText("settings.json", json);
Serge
  • 40,935
  • 4
  • 18
  • 45