SQL Server-OPENJSON解析JSON文本

时间:2018-06-20 14:14:33

标签: json sql-server

在定义为JSON的列中有以下nvarchar(max)文本:

{"country":
    {"id":642,
    "name":"ROMANIA",
    "nameEn":"ROMANIA",
    "isoAlpha2":"RO",
    "isoAlpha3":"ROU",
    "currencyCode":"RON",
    "requireState":false,
    "addressType":1,
        "streetTypes":
        [
            {"name":"str.","nameEn":"str."},
            {"name":"","nameEn":""},
            {"name":"ale.","nameEn":"ale."},
            {"name":"int.","nameEn":"int."},
            {"name":"fdt.","nameEn":"fdt."},
            {"name":"pta.","nameEn":"pta."},
            {"name":"bld.","nameEn":"bld."},
            {"name":"drm.","nameEn":"drm."},
            {"name":"cal.","nameEn":"cal."},
            {"name":"sos.","nameEn":"sos."}
        ],
    "quarterTypes":[],
    "postCodeFormats":["","NNNNNN"]
    }
}

我想提取ID的值为642,并且使用了以下语句,但是我想知道这是否是正确的方法:

SELECT TOP 1 VALUE
FROM OPENJSON(@jsonBody, '$.country')

如何不使用TOP 1仅提取id元素的值?

2 个答案:

答案 0 :(得分:0)

更精确的方法是实际指示您要返回ID,而不是假设它始终是第一个值。

SELECT *
FROM OPENJSON(@, N'$.country')
WITH (id int '$.id')

答案 1 :(得分:0)

听起来像JSON_VALUE的工作:

SELECT JSON_VALUE(@jsonBody, '$.country.id')

文档中还包含有关如何访问值数组的示例。