-1

I have below Json structure

{
  "Name": "abc",
  "Grade": "a"
}

Now, i want to add values to the attributes which is location in hierarchy. For example, i want to add value just like below -

Name.Lavel-1.Lavel-2.Lavel-3.Direaction = "East"

As above, i have to add value of "Direction" attribute, which itself is located inside Lavel-3 attribute which does not exists. Same way, Lavel-1 and Lavel-2 does not even exist at the time of addition.

So, my requirement is to add the required hierarchy and then add the value. So, after the addition, the json should look like below

{
  "Name": "Jack",
  "Grade": "A",
  "Lavel-1": {
    "Lavel-2": {
      "Lavel-3": {
        "Direction": "East"
      }
    }
  }
}

I google and tried some solutions, but most of them are simple adding/Updating the values to an existing path,i.e, where the hierarchy is already available,and the modification is done only of the Leaf node.

Need help, if we can achieve this with efficiency.

Lalit
  • 19
  • 5
  • 1
    Possible duplicate of [How to add a new JProperty to a JSON based on path?](https://stackoverflow.com/q/56427214/10263) – Brian Rogers Jul 29 '20 at 20:17
  • [Merge two JTokens into one](https://stackoverflow.com/q/37756656/3744182) might also meet your needs. You could create the required `"Lavel-1"` object hierarchy as shown in the answer below in a fresh `JObject`, and then merge it onto a `JObject` containing the existing JSON. – dbc Jul 30 '20 at 04:13

2 Answers2

1

One way is to add new JObjects and JProperties:

var jstring= @"{
  ""Name"": ""abc"",
  ""Grade"": ""a""
}";

var json = JObject.Parse(jstring);
json.Add(
    new JProperty("Lavel-1",
        new JObject(new JProperty("Lavel-2",
            new JObject(new JProperty("Lavel-3",
                new JObject(new JProperty("Direction","East"))
            ))
        ))
    )
);
Magnetron
  • 7,495
  • 1
  • 25
  • 41
  • Thank for your response. Hierarchy is not static. its dynamic.. Also, existence of hierarchy nodes are not known in advance, i.e "Lavel-1" & "Lavel-2" may already exists, so if that is case, then only two node "Lavel-3" and "Direction" needs to be created and added. So, requirement here is, Nodes in hierarchy is not fixed.. – Lalit Jul 29 '20 at 17:44
  • 3
    @Lalit - then you should [edit](https://stackoverflow.com/posts/63158897/edit) your question and provide a [mcve] stating **all** of your requirements. Your current question states *my requirement is to add the required hierarchy and then add the value.* not *add or update*. Incidentally there's nothing hardwired about the property names `"Lavel-1"` in this answer, they can easily be extracted out into string variables, so this looks to answer your question as it is currently written. – dbc Jul 29 '20 at 18:02
0

Thank you Magnetron for the response. updating answer which helps me to get my needs as it can help other dev as well.

I found the below steps on another stackoverflow thread which satisfy my need. I change a little bit. Below code block will add the path ( if not exists) and set the value.

 private void AddPropertyToJTokenWithValue(JToken jtoken, string tokenPath, string value)
        {
            if (jtoken == null || tokenPath == null)
            {
                return;
            }

            var pathParts = tokenPath.Split('.');
            foreach (var pathPart in pathParts)
            {
                var partNode = jtoken.SelectToken(pathPart);
                if (partNode == null)
                {
                    try
                    {
                        if (pathPart != pathParts.Last())
                        {
                            ((JObject)jtoken).Add(pathPart, new JObject());
                            partNode = jtoken.SelectToken(pathPart);
                        }
                        else
                        {
                            ((JObject)jtoken).Add(pathPart, value);
                            partNode = jtoken.SelectToken(pathPart);
                        }
                    }
                    catch (Exception ex)
                    {
                        // log
                         return;
                    }
                }

                jtoken = partNode;
            }

            return;
        }
Lalit
  • 19
  • 5