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?
One possible solution is to use
OPENJSON()
to extract each JSON object from the stored JSON array andSUSBTRING()
andSTRING_AGG()
to build the final output:Table:
Table:
Result: