We've got a SQL query where we create a JSON file with for JSON Path. We want to merge 2 JSON objects into 1 JSON. But we struggle with the code how to accomplish this task.
We tried JSON_MODIFY to merge them together using append. But this did not work for us.
What we'd like to do is this, we have 2 seperate json objects and we want to merge them as one.
Json Object A:
{
"ID" : 0,
"Name" : "a name",
"Description" : "a description"
}
and Json Object B
"Nodes" : [
{
"NodeID" : 10,
"NodeName" : "Node 0"
},
{
"NodeID" : 11,
"NodeName" : "Node 1"
}
]
What we want to have:
{
"ID" : 0,
"Name" : "a name",
"Description" : "a description",
"Nodes" : [
{
"NodeID" : 10,
"NodeName" : "Node 0"
},
{
"NodeID" : 11,
"NodeName" : "Node 1"
}
]
}
Our current SQL Query looks like this:
set @JsonCourse = ( select c.name, c.id, c.description from dbo.courses c where c.id = @id for json path)
set @JsonNodes = ( select n.id, n.name from dbo.nodes n where n.courseId = @id for json path, root('Nodes'))
set @CompleteJson = JSON_MODIFY(@JsonCourse,'append $',JSON_QUERY(@JsonNodes));
print @CompleteJson
But our result is like this:
[
{
"ID" : 0,
"Name" : "a name",
"Description" : "a description"
},
{
"Nodes" : [
{
"NodeID" : 10,
"NodeName" : "Node 0"
},
{
"NodeID" : 11,
"NodeName" : "Node 1"
}
]
}
]
Note: we've used hypothetical data here.
How do we fix this with JSON_MODIFY?