I have a JArray as below, how to JArray ReplaceAll where is_closed=false? I expect to set is_closed to true and set closed_dt to DateTime.Now for is_closed = false How to do accomplish this JArray use case scenario with C#?
[
{
"oppty": 50,
"extras": {
"is_closed": false,
"closed_dt": ""
}
},
{
"oppty": 51,
"extras": {
"is_closed": true,
"closed_dt": ""
}
},
{
"oppty": 52,
"extras": {
"is_closed": false,
"closed_dt": ""
}
}
]
I tried C# codes below:
foreach (var oppty in jaOppty.Select(o => o.ToObject<JObject>()).Where(o => (bool)o["extras"]["is_closed"] == false))
{
JObject joExtras = (JObject)chat["extras"];
joExtras["is_closed"] = true;
joExtras["closed_dt"] = DateTime.Now
}
but it doesn't update the jaOppty, so I thought I have to use ReplaceAll but didn't get an idea on how to do this?
CodePudding user response:
try this code
var jsonParsed = JArray.Parse(json);
foreach (var item in jsonParsed)
{
if (!(bool)item["extras"]["is_closed"])
{
item["extras"]["closed_dt"] = DateTime.Now;
item["extras"]["is_closed"] = true;
}
}
json = jsonParsed.ToString();
result
[
{
"oppty": 50,
"extras": {
"is_closed": true,
"closed_dt": "2022-06-22T10:56:52.3484234-02:30"
}
},
{
"oppty": 51,
"extras": {
"is_closed": true,
"closed_dt": ""
}
},
{
"oppty": 52,
"extras": {
"is_closed": true,
"closed_dt": "2022-06-22T10:56:52.351146-02:30"
}
}
]