Search code examples
arraysjsonsql-servert-sql

Get a specific JSON value when I have multiple array elements


I have a JSON string that looks like this:

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

For a given tagType (e.g. Geography) how do I get the tagValue (e.g. US)

I've tried various ugly select queries. I feel there has to be an elegant way to do this

This query (as part of a bigger query) works

[Geography] = (SELECT tagValue 
                            FROM OPENJSON(REPLACE(p.tags, '''', '"')) 
                            WITH (tagType VARCHAR(255) '$.tagType', tagValue VARCHAR(255) '$.tagValue')
                            WHERE tagType = 'Geography')

Solution

  • Almost correct with 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 tagType, tagValue
    FROM OPENJSON(@j)  
    WITH (
        tagType varchar(20),
        tagValue varchar(20)
    )
    WHERE tagType = 'Geography'
    

    result:

    tagType tagValue
    Author Anne Author
    Business the bidness
    Geography US
    Subscription A subscription

    UPDATE:

    SELECT tagValue
    FROM OPENJSON(@j)  
    WITH (
        tagType varchar(20),
        tagValue varchar(20)
    )
    WHERE tagType = 'Geography'
    

    Result would be: "US"