Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON.NET: How to insert an existing JSON into the middle of another?

Tags:

.net

json.net

Is there any easy way to insert an existing JSON file into the middle of another?

I have seen others asking how to merge them but I think my problem is unique, I can't seem to find any info on it.

Edit

Here is first JSON.

{
   Name: "test1",
   Items: {
       Name: "test1items"
   }
}

I need to insert a second JSON (it's valid json) into a new property called "data" on the first json, the data property you don't see as it doesn't exist, it's below Items. Like so

{
   Name: "test1",
   Items: {
       Name: "test1items",
       Data: ........
   }
}

So the idea is to use some sort of reader on the first json and find Items.Name and add a new property "Data" and merge in the second JSON.

I haven't included the second JSON as it really shouldn't matter, it's a valid json string.

I have everything in strings so I can parse them etc?

like image 871
Martin Avatar asked Jan 27 '26 23:01

Martin


1 Answers

string json1 = @"
    {
        Name: ""test1"",
        Items: {
            Name: ""test1items""
        }
    }";
string json2 = @"
    {
        ""SomeField"": ""SomeData""
    }";

var obj1 = JObject.Parse(json1);
var obj2 = JObject.Parse(json2);


obj1["Items"]["Data"] = obj2;

var newJson = obj1.ToString();

And the output:

{
  "Name": "test1",
  "Items": {
    "Name": "test1items",
    "Data": {
      "SomeField": "SomeData"
    }
  }
}
like image 53
EZI Avatar answered Jan 31 '26 01:01

EZI



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!