I have SQL Server 2016 (v13) installation where I am trying to parse a column with JSON data. The data in the column RequestData
is in the following format:
[
{ "Name": "SourceSystem", "Value": "SSValue" },
{ "Name": "SourceSystemId", "Value": "XYZ" }
]
[
{ "Name": "SourceSystemId", "Value": "SSID" },
{ "Name": "SourceSystem", "Value": "SSVALUE2" }
]
What I need to get are the values for the SourceSystem
element of the JSON object in each row. And here is my Select statement:
SELECT TOP 2
JSON_VALUE(RequestData, '$[0].Value') AS SourceSystem
FROM
RequestDetail
But, due to the order of the JSON elements in the column’s data, the values being returned for the SourceSystem
column are not correct.
SSValue, SSID
Please note, I need to be able to parse the JSON elements so that the SourceSystem
column will have correct values, i.e SSValue and SSValue2.
I have also tried JSON_Query
using some online examples but no luck so far.
Thank you!
Edit
The Question has been modified by someone after I posted, so I am adding this for clarification: Each row of data, as given in the Question, will have several ‘Name’ elements and those Name elements can be SourceSystem or SourceSystemId. The Question shows data from two rows from the database table’s column, but, as you can see, the SourceID and SourceSystemId elements in each row are not in the same order between the first and the second row. I simply need to parse SourceSystem element per row.
3
Answers
Presumably you need
OPENJSON
here, notJSON_VALUE
:When you want to use JSON_VALUE, just select the correct (needed) values:
output:
When you only need values from "SourceSystem", you can always do:
output:
see: DBFIDDLE
EDIT:
This will give:
Using openjson, to get all the data in columns you can use it as any othe table
fiddle