Address JObject with a dynamic number of elements

Viewed 57

I have a C# JSON.NET JObject where I am iterating through each node and leaf node using the approach here: https://www.anotherdevblog.net/posts/flattening-json-in-json-net

I am looking to write/update to the original JObject for certain node/leaf hierarchies (example here of fields.phone). The issue I'm having is passing the parameters to different levels, e.g. [1][2][3].

Is it necessary to do a dynamic C# query string here (my default thinking is a SQL dynamic query-like approach) or is there a cleaner way of doing this?

Thanks!

////READ JSON
JObject ccdmObj = p.readJson(workDir, "ccdmRead.json");

////ENUMERATE JSON
foreach (var jValue in ccdmObj.GetLeafValues())
{
    if (jValue.Path == "fields.phone")
    {
        jValue.Value = "123"; // UPDATING VALUE IN ENUMERATOR ONLY
        ccdmObj["fields"]["phone"] = "blah"; // UPDATING JOBJECT MANUALLY
        ccdmObj[$"{jValue.Path}"] = "blah"; // UPDATING JOBJECT DYNAMICALLY - NOT WORKING
    }
    Console.WriteLine($"{jValue.Path} = {jValue.Value}");
}

Example output from WriteLine:

id = 12345
fields.firstName = John
fields.lastName = Smith
fields.DOB = 1980-01-01
fields.phone = 123
fields.address.residential.line1 = Unit 4
fields.address.residential.line2 = 3 Main st
1 Answers

You can just use Replace:

foreach (var jValue in ccdmObj.GetLeafValues())
{
    if (jValue.Path == "fields.phone")
    {
       jValue.Replace(new JValue("blah"));
    }
}
Related