I have a highly-unstructured JSON string, coming as a response of calling a REST API:
{
"info": "Test Json Structure",
"Owner": "Self-Owned",
"managedObjects": [{
"Name": "Device1",
"Class": "A"
}, {
"Name": "Device2",
"Class_145": "Ax01",
"Class_11": "B",
"Type_125478": {
"Model": "1",
"Manufacturer": "External"
},
"Type_SD": {
"Model": "00",
"Manufacturer": "Internal"
}
}, {
"Name": "Device3",
"Class_x": "Cx11",
"Class_T": "C8Y",
"Type": {
"Model": "1x",
"Manufacturer": "Internal"
}
}
]
}
How can I dynamically parse this object using T-SQL, so that all child elements to represent columns of a table? More importantly, how to deal with Type
, Type_125478
, Type_SD
objects, where in fact they have the same structure (Model, Manufacturer
) but some how their names are different. Also keep in mind that the device may send a new identifier (Type_XYZ
), which didn't exist before, but luckily has the same structure (Model, Manufacturer
).
You might use something like this to explode the whole lot into a tabular structure and proceed with this (needs a SQL-Server version v2016+):
--the query
--the result
Hint: You might add
B.[key]
to the result as an object identifier.The idea in short
OPENJSON
to get into your JSON. TheWITH
-clause allows to address the JSON-props as columns. We return themanagedObejcts
as JSON themselve.OPENJSON
to dive into the managed objects.value
into anotherOPENJSON
.value
can be interpreted as JSON on its own, we use one moreOPENJSON
, this time with aWITH
-clause again to get the internal props as columns.You can insert this result into a table (declared, temp, physical...) and continue with this easy-to-read set.