简体   繁体   中英

How to retrieve specific JSON value from a column containing a JSON array

I have this JSON array in a SQL Server table:

[
    {
        "FieldName": "DateCreated",
        "FieldValue": "10/22/2020"
    },
    {
        "FieldName": "IsMember",
        "FieldValue": "false"
    },
    {
        "FieldName": "EntityId",
        "FieldValue": "ABC123"
    }
]

I want to fetch only the FieldValue of the EntityId object, so the output should be only ABC123 .

I have this query

SELECT JSON_VALUE(JsonColumnData, '$[2].FieldValue') AS EntityId
FROM MyTable

This returns the EntityId value, but the thing is that I have no guarantee that the EntityId will always be in the same position of the JSON array.

Is it possible to have the select return the EntityId regardless of its position in the JSON array?

You can use OPENJSON() to query the data and just filter the row(s) that contain EntityId...

create table dbo.MyTable (
  JsonColumnData nvarchar(max)
);

insert dbo.MyTable (JsonColumnData) values (N'[
    {
        "FieldName": "DateCreated",
        "FieldValue": "10/22/2020"
    },
    {
        "FieldName": "IsMember",
        "FieldValue": "false"
    },
    {
        "FieldName": "EntityId",
        "FieldValue": "ABC123"
    }
]');

select FieldValue as EntityId
from dbo.MyTable
cross apply openjson(JsonColumnData) with (
  FieldName nvarchar(11),
  FieldValue nvarchar(11)
)
where FieldName = N'EntityId';

Which yields...

EntityId
---------
ABC123

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM