Search code examples
c#jsonsystem.text.json

How to update json property value and save back to file


I have a json file as follows

{
    "desc": "my desc",
    "lang": "en",
    "issue": {
        "date": "2024-09-01",
        "title": "Empowering Razor Club"
    },
    "stars": [
        {
            "id": 1,
            "value": 5
        },
        {
            "id": 2,
            "value": 4
        }
    ]
}

This json structure is fixed and won't change but the value can change. I want create a method to update particular property value and save back to file.

Using Newtonsoft.Json SelectToken is easy by placing dot (.) for nested properties or even arrays such as "issue.title" or "stars[0].value". When it comes to System.Text.Json I find it harder.

private void UpdateJsonValue(string path, object value)
{
    var json = "the above sample"
    var node = JsonNode.Parse(json);
    node[path] = JsonValue.Create(value); //error's here
    
    json = node.ToJsonString();
    //save json to file
}

UpdateJsonValue("issue.title", "Hello World");
UpdateJsonValue("stars[[1].value", 5);

So, how to get JsonNode with nested properties?


Solution

  • Consider the following method:

    void UpdateJsonValue(object value, params object[] path)
    {
        var json = File.ReadAllText("test.json");
        var node = JsonNode.Parse(json);
    
        var temp = node;
        foreach (var item in path)
        {
            if (item is string propertyName)
                temp = temp[propertyName];
    
            if (item is int index)
                temp = temp[index];
        }
        temp.ReplaceWith(value.ToString());
    
        Console.WriteLine(node);    
    }
    

    Use it in the following way:

    UpdateJsonValue("Hello World", "issue", "title");
    UpdateJsonValue(555, "stars", 1, "value");