Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
499 views
in Technique[技术] by (71.8m points)

c# - How to add a new JProperty to a JSON based on path?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...