Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a new JProperty to a JSON based on path?

Tags:

json

c#

json.net

There is a large JSON file (about a thousand lines). The task is to update existing JProperties, or add new JProperties in a specific location in the structure. The location of the new texts are based on the JToken.Path property. For example, this is the start of the JSON:

"JonSnow": {
    "Direwolf": {
        "Name": "Ghost",
        "Color": "White",
    }
}
"DanaerysTargaryen": {
    "Dragons": {
        "Dragon1": {
            "Name": "Drogon",
        }
    }
    "Hair": {
        "Color": "White"
    }
}

Now the JSON must be updated using a given list of JToken paths and the corresponding values.

The first possibility is, the JProperty corresponding to the path might already exist, in which case the value needs to be updated. I am already successfully implementing this with JToken.Replace().

The second possibility is, the JProperty does not exist yet and needs to be added. For example, I need to add "DanaerysTargaryen.Dragons.Dragon1.Color" with the value "Black".

I know I can use the JSON.Net Add() method, but to use this only the final child token of the path can be missing from the JSON. For example, I can use

JObject ObjToUpdate= JObject.Parse(jsonText);
JObject Dragon = ObjToUpdate["DanaerysTargaryen"]["Dragons"]["Dragon1"] as JObject;
Dragon.Add("Color", "Black"));

But what about if I need to add "JonSnow.Weapon.Type" with the value "Longsword"? Because "Weapon" does not exist yet as a JProperty, and it needs to be added along with "Type" : "Longsword". With each path, it is unknown how much of the path already exists in the JSON. How can this be parameterised?

// from outside source: Dictionary<string, string> PathBasedDict 
// key: Jtoken.Path (example: "JonSnow.Weapon.Type")
// value: new text to be added (example: "Longsword")

foreach(KeyValuePair entry in PathBasedDict)
{
    string path = entry.Key;
    string newText = entry.Value;

    if (ObjToUpdate.SelectToken(path) != null)  
        { ObjToUpdate.SelectToken(path).Replace(newText); }

    else AddToJson(path, newText);
}

What should AddToJson() look like? Iterating through the entire path and checking each possible JProperty to see if it exists, and then adding the rest underneath, seems very cumbersome. Is there a better way to do this? Any Json.NET tricks I am unaware of? I am not even sure how the iteration could be parameterised.

like image 376
user9729207 Avatar asked Jun 03 '19 12:06

user9729207


2 Answers

There are a few ways of going about this. Here are two of them.

  1. To go along with your existing code, split the path by '.', then iterate over them. If the path is not there, create it with Add. Otherwise, if we're on the last part of the path, just add the value.

    var json = JObject.Parse(@"{""DanaerysTargaryen"":{""Dragons"":{""Dragon1"":{""Name"": ""Drogon""}},""Hair"": {""Color"": ""White""}}}");
    var toAdd = "DanaerysTargaryen.Dragons.Dragon1.Color";
    var valueToAdd = "Black";
    var pathParts = toAdd.Split('.');
    JToken node = json;
    for (int i = 0; i < pathParts.Length; i++)
    {
        var pathPart = pathParts[i];
        var partNode = node.SelectToken(pathPart);
        if (partNode == null && i < pathParts.Length - 1)
        {
            ((JObject)node).Add(pathPart, new JObject());
            partNode = node.SelectToken(pathPart);
        }
        else if (partNode == null && i == pathParts.Length - 1)
        {
            ((JObject)node).Add(pathPart, valueToAdd);
            partNode = node.SelectToken(pathPart);
        }
        node = partNode;
    }
    
    Console.WriteLine(json.ToString());
    

(Example on dotnetfiddle.net)

  1. Otherwise, you could create a separate JObject that represents the node(s) you want to add, then merge them.

     var json = JObject.Parse(@"{""DanaerysTargaryen"":{""Dragons"":{""Dragon1"":{""Name"": ""Drogon""}},""Hair"": {""Color"": ""White""}}}");
     var toMerge = @"{""DanaerysTargaryen"":{""Dragons"":{""Dragon1"":{""Color"":""Black""}}}}";
     var jsonToMerge = JObject.Parse(toMerge);
     json.Merge(jsonToMerge);
     Console.WriteLine(json.ToString());
    

(Example on dotnetfiddle.net)

like image 142
Heretic Monkey Avatar answered Nov 01 '22 10:11

Heretic Monkey


Based on first approach from Heretic Monkey's answer, here is an extension method:

public static class JObjectExtensions
{
    /// <summary>
    /// Replaces value based on path. New object tokens are created for missing parts of the given path.
    /// </summary>
    /// <param name="self">Instance to update</param>
    /// <param name="path">Dot delimited path of the new value. E.g. 'foo.bar'</param>
    /// <param name="value">Value to set.</param>
    public static void ReplaceNested(this JObject self, string path, JToken value)
    {
        if (self is null)
            throw new ArgumentNullException(nameof(self));
        
        if (string.IsNullOrEmpty(path))
            throw new ArgumentException("Path cannot be null or empty", nameof(path));

        var pathParts = path.Split('.');
        JToken currentNode = self;
        
        for (int i = 0; i < pathParts.Length; i++)
        {
            var pathPart = pathParts[i];
            var isLast = i == pathParts.Length - 1;
            var partNode = currentNode.SelectToken(pathPart);
            
            if (partNode is null)
            {
                var nodeToAdd = isLast ? value : new JObject();
                ((JObject)currentNode).Add(pathPart, nodeToAdd);
                currentNode = currentNode.SelectToken(pathPart);
            }
            else
            {
                currentNode = partNode;

                if (isLast)
                    currentNode.Replace(value);
            }
        }
    }
}
like image 38
yurislav Avatar answered Nov 01 '22 08:11

yurislav