Reputation: 24308
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.
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?
Upvotes: 3
Views: 2546
Reputation: 15354
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"
}
}
}
Upvotes: 6