I am working on a SQL table with a column with JSON value. Each row of that column is string value in JSON structure. This JSON structure is always one array that contains one or more objects of one item. The number and key words of objects can vary. For instance, a first row might look like this:
[{"Page View":"Page"}
,{"Search Data":"9"}
,{"Search Distance":"undefined"}
,{"Search Location":"undefined"}
,{"Search Filters":"{}"}
,{"Search No Restrictions":"undefined"}
,{"Search Term":"Services"}
,{"Search Type":"Id"}]
The second row value might look like this:
[{"Page Type":"Service"}
,{"Organization ID":"111555666"}
,{"Service ID":"333444"}
,{"refUrl":"https://randomURL"}]
I am trying to convert these values to be one object with multiple elements
So the first row looks like this:
{"Page View":"Page"
,"Search Data":"9"
,"Search Distance":"undefined"
,"Search Location":"undefined"
,"Search Filters":"{}"
,"Search No Restrictions":"undefined"
,"Search Term":"Services"
,"Search Type":"Id"}
And the second row looks like this:
{"Page Type":"Service"
,"Organization ID":"111555666"
,"Service ID":"333444"
,"refUrl":"https://randomURL"}
I tried this method:
SELECT FRUA.Id,
REPLACE(REPLACE(REPLACE(REPLACE(JSON_column, '{',''),'}',''), '[','{'),']','}')
FROM test.table
This works, but it can change unintended { or [ in value like "Search Filters":"{}", or can wreck a nested element. Is there a better way to accomplish this on SQL Server Azure 12.0.2000.8?
It's an unnamed JSON array of JSON objects. To access the elements of the array the answer uses JSON_QUERY and column offset. Once the JSON objects have been extracted from the array into columns, the solution uses JSON_VALUE to extract the field values. Once the field values have extracted into columns, the resulting table is serialized using FOR JSON PATH and specifies WITHOUT_ARRAY_WRAPPER.
JSON Data
Query
Output