Archive
Archive for June 2, 2017
Parsing nested JSON in customized SQL Tabular format – MSDN TSQL forum
June 2, 2017
Leave a comment
–> Question:
Basically I have a JSON file output that I want to put into a SQL table, but no matter what syntax I try it doesn’t seem to be working.
This is my sample JSON file contents:
{
"destination_addresses":[
"Orlando, FL, USA"
],
"origin_addresses":[
"New York, NY, USA"
],
"rows":[
{
"elements":[
{
"distance":{
"text":"1,072 mi",
"value":1725756
},
"duration":{
"text":"15 hours 40 mins",
"value":56405
},
"status":"OK"
}
]
}
],
"status":"OK"
}
What I want is a SQL table that has 2 columns, column 1 will be item names (Destination Address,Origin Address, Distance Text, Distance Value, Duration Text & Duration Value) and column 1 will be the actual data.
I can get OPENJSON to do what I want for destination address & origin address but when I try and using OPENJSON to read the nested items that exist in ‘rows – > elements’ I can’t seem to pick them up. Can anyone help with the right syntax?
–> Answer:
declare @str varchar(4000) =
N'{
"destination_addresses":[
"Orlando, FL, USA"
],
"origin_addresses":[
"New York, NY, USA"
],
"rows":[
{
"elements":[
{
"distance":{
"text":"1,072 mi",
"value":1725756
},
"duration":{
"text":"15 hours 40 mins",
"value":56405
},
"status":"OK"
}
]
}
],
"status":"OK"
}'
SELECT
CONCAT_WS(' ',Destination_Addresses, Origin_Addresses,Distance_Text,
Distance_Value,Duration_Text,Duration_Value) as Col1
,@str as Col2
FROM OPENJSON (@str)
WITH (
Destination_Addresses VARCHAR(1000) '$.destination_addresses[0]',
Origin_Addresses VARCHAR(1000) '$.origin_addresses[0]',
Distance_Text VARCHAR(1000) '$.rows[0].elements[0].distance.text',
Distance_Value VARCHAR(1000) '$.rows[0].elements[0].distance.value',
Duration_Text VARCHAR(1000) '$.rows[0].elements[0].duration.text',
Duration_Value VARCHAR(1000) '$.rows[0].elements[0].duration.value'
) AS Orders
Categories: SQL Server 2016, SQL Server Questions
JSON SQL, MSDN TSQL forum




