Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SQL Server JSON_QUERY Select Json object based on value

I have the following JSON data in a SQL Server table:

{
    "Mapping": [
        {
            "SourceFieldId": 46,
            "TargetField": {
                "output_field_description": "Last Name",
                "output_header_field": "Last Name",
                "required": "Y",
                "data_type": "TEXT",
                "date_format": "",
                "number_of_decimals": "",
                "max_length": 30,
                "field": 1
            }
        },
        {
            "SourceFieldId": 46,
            "TargetField": {
                "output_field_description": "Last Name",
                "output_header_field": "Last Name",
                "required": "Y",
                "data_type": "TEXT",
                "date_format": "",
                "number_of_decimals": "",
                "max_length": 30,
                "field": 1
            }
        }
    ]
}

I am trying to grab the object based on the SourceFieldID.

I’ve tried a few variations of this, with no luck:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

SELECT
    JSON_query(MapJSON, '$.Mapping')  
FROM
    MapHistories 
WHERE
    JSON_VALUE(MapJSON, '$.Mapping.SourceFieldID') = 1

Is this possible?

>Solution :

You can do it using OPENJSON to parses the json as the first argument and returns one or more rows containing data from the JSON objects :

SELECT SalesOrderJsonData.*
FROM MapHistories AS Tab
CROSS APPLY OPENJSON(Tab.MapJSON, N'$.Mapping') WITH (
    SourceFieldId int N'$.SourceFieldId',
    TargetField nvarchar(max) N'$.TargetField' AS JSON 
    ) AS SalesOrderJsonData
where SalesOrderJsonData.SourceFieldId = 46

Demo here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading