当我有多个数组元素时获取特定的 JSON 值

问题描述 投票:0回答:1

我有一个如下所示的 JSON 字符串:

[{'tagType': 'Author', 'tagValue': 'Anne Author'}, {'tagType': 'Business', 'tagValue': 'the bidness'}, {'tagType': 'Geography', 'tagValue': 'US'}, {'tagType': 'Subscription', 'tagValue': 'A subscription'}]

对于给定的 tagType(例如地理),如何获取 tagValue(例如 US)

我尝试过各种丑陋的选择查询。我觉得必须有一种优雅的方式来做到这一点

此查询(作为更大查询的一部分)有效

[Geography] = (SELECT tagValue 
                            FROM OPENJSON(REPLACE(p.tags, '''', '"')) 
                            WITH (tagType VARCHAR(255) '$.tagType', tagValue VARCHAR(255) '$.tagValue')
                            WHERE tagType = 'Geography')
arrays json sql-server t-sql
1个回答
0
投票

Openjson 几乎正确

declare @j nvarchar(max)= N'[{"tagType": "Author", "tagValue": "Anne Author"}, {"tagType": "Business", "tagValue": "the bidness"}, {"tagType": "Geography", "tagValue": "US"}, {"tagType": "Subscription", "tagValue": "A subscription"}]'

select * 
from OPENJSON(@j)  
WITH (
    tagType varchar(20),
    tagValue varchar(20)
) 

结果:

标签类型 标签值
作者 安妮作者
商业 出价
地理 美国
订阅 订阅
© www.soinside.com 2019 - 2024. All rights reserved.