I want to extract Information from an Array inside a JSON string in a Microsoft SQL Server database.
If I have a JSON object like this:
CREATE TABLE myTable([Id] int, [JsonInfo] varchar(max));
INSERT INTO myTable ([Id], [JsonInfo])
VALUES (1,
'{
"$id": "1",
"Id": "32766177-18c7-4c2d-bbb5-02588a73ff72",
"Metadata": [
{
"Identifier": "Identifier1",
"Value": "aaa"
},
{
"Identifier": "Identifier2",
"Value": "bbb"
},
{
"Identifier": "Identifier3",
"Value": "ccc"
},
],
}'
);
The only way I found to access the entire Array was:
SELECT Id, value AS Metadata
FROM myTable t
CROSS APPLY OPENJSON( JSON_QUERY(t.JsonInfo, '$.Metadata'))
To access the information in the array, I did the following:
SELECT
JSON_VALUE(Metadata, '$.Identifier') AS Identifier,
JSON_VALUE(Metadata, '$.Value') AS Value
FROM
(SELECT Id, value AS Metadata
FROM myTable t
CROSS APPLY OPENJSON( JSON_QUERY(t.JsonInfo, '$.Metadata'))
);
My result is:
Identifier | Value
------------+--------
Identifier1 | aaa
Identifier2 | bbb
Identifier3 | ccc
The result I should be:
Identifier1 | Identifier2 | Identifier3
------------+-------------+------------
aaa | bbb | ccc
The result with non matching records:
Identifier1 | Identifier2 | Identifier3 |Identifier4
------------+-------------+-------------+-----------
aaa | bbb | ccc | NULL
aaa | bbb | NULL | ddd
I know I could transpose it with PIVOT but it seems too complex for this scenario.
Any suggestions on how I could achieve this easily?
JSON_QUERRY,JSON_VALUE(Metadata, $.Identifier)), the JSON is not valid. Does$.Metadataalways have fixed count of items?$.Metadatais of dynamic rangemyTabletable has$.MetadataJSON array with five items, what is the expected result for both rows?