简体   繁体   English

将列中的嵌套 JSON 解析为 SQL Server 中的表

[英]Parse nested JSON in a column to Table in SQL Server

I have a table that only have one column and the records are in json format as shown below:我有一个只有一列的表,记录采用 json 格式,如下所示: 在此处输入图片说明

The sample of each row is:每行的样本为:

{
    "id": "51cf9ff0-0ed5-11eb-8887-53248e3b2424",
    "attributes": {
        "source": "Google",
        "medium": "cpc",
        "visit_route": [
            {
                "time_on_page": 5,
                "page_title": "Dedicated Servers"               
            },
            {
                "time_on_page": 1,
                "page_title": "Partner Programme"                
            }
        ],
        "keyword": null,
        "visit_length": 6,
        "started_at": "2020-10-15T10:56:31.51Z",
        "ga_client_ids": [
            "1213599109.1602733400"
        ],
       "lead_id": "597b4cd6-d8fb-11e6-adad-17d0cee77142_ayRRmwDGKhjjSgdcMGDMGf"
    }
}

The outcome should look like below:结果应如下所示:

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|id                                   |source |medium |visit_route                                                                                                  |Keyword|
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|51cf9ff0-0ed5-11eb-8887-53248e3b2424 |Google |cpc    |[{"time_on_page": 5,"page_title": "Dedicated Servers"},{"time_on_page": 1,"page_title": "Partner Programme"}]| Null  |

This sample is in each rows.此示例位于每一行中。 I am new to parsing json in sql and have tried using the script below:我是在 sql 中解析 json 的新手,并尝试使用以下脚本:

 select id ,
        attributes
from [StageDB].[dbo].[LeadFeeder_visits_json] 
  cross apply openjson(jsonObj)
  WITH (   
             id   nvarchar(100) ,  
                
             attributes nvarchar(max)   
                
        )

But the result I got as shown below:但是我得到的结果如下图:

在此处输入图片说明

I really need help.我真的需要帮助。

You would need to openjson() twice: once to unnest jsonObj , and another time to access the nested attributes:您需要openjson()两次:一次jsonObj嵌套jsonObj ,另一次访问嵌套属性:

select x.id, y.source, y.medium, y.visit_route
from [StageDB].[dbo].[LeadFeeder_visits_json] l
cross apply openjson(l.jsonObj) with(   
    id          nvarchar(100),
    attributes  nvarchar(max) as json
) x
cross apply openjson(x.attributes) with (
    source      nvarchar(100),
    medium      nvarchar(100),
    visit_route nvarchar(max) as json
) y

Note that you need as json when extracting nested json content.请注意,提取嵌套的 json 内容时需要as json

If you'll have multiple sets of ATTRIBUTES, then GMB is correct with the second cross apply .如果您有多组 ATTRIBUTES,则 GMB 与第二个cross apply是正确的。 If only one set, then you can get by with a single cross apply .如果只有一组,那么您可以通过一个cross apply

Example例子

Select B.*
 From  YourTable A
 Cross Apply OpenJSON(jsonObj) WITH (
        id          varchar(100) '$.id',
        source      varchar(100) '$.attributes.source',
        medium      varchar(100) '$.attributes.medium',
        visit_route nvarchar(MAX) '$.attributes.visit_route' AS JSON,
        keyword     varchar(100) '$.attributes.keyword'
    ) B

Returns退货

在此处输入图片说明

An alternative to OPENJSON is to use JSON_VALUE and JSON_QUERY to pick out the pathways needed. OPENJSON的替代OPENJSON是使用JSON_VALUEJSON_QUERY来挑选所需的路径。 The JSON functions can optionally specify whether or not a field is strictly required. JSON 函数可以选择指定是否严格要求某个字段。 For example, in the code the first JSON_VALUE specifies the 'id' to be 'strict'-ly present in the JSON.例如,在代码中,第一个JSON_VALUE将“id”指定为“严格”存在于 JSON 中。 If the 'id' field is not present the JSON_VALUE function will return an error如果“id”字段不存在, JSON_VALUE函数将返回错误

JSON in a table表中的 JSON

drop table if exists #json;
go
create table #json(
  jsonObj                   nvarchar(max) not null);
go

insert #json(jsonObj) values (N'{
    "id": "51cf9ff0-0ed5-11eb-8887-53248e3b2424",
    "attributes": {
        "source": "Google",
        "medium": "cpc",
        "visit_route": [
            {
                "time_on_page": 5,
                "page_title": "Dedicated Servers"               
            },
            {
                "time_on_page": 1,
                "page_title": "Partner Programme"                
            }
        ],
        "keyword": null,
        "visit_length": 6,
        "started_at": "2020-10-15T10:56:31.51Z",
        "ga_client_ids": [
            "1213599109.1602733400"
        ],
       "lead_id": "597b4cd6-d8fb-11e6-adad-17d0cee77142_ayRRmwDGKhjjSgdcMGDMGf"
    }
}');

Query询问

select json_value(jsonObj, N'strict $.id') id,
       json_value(jsonObj, N'$.attributes.source') [source],
       json_value(jsonObj, N'$.attributes.medium') [medium],
       json_query(jsonObj, N'$.attributes.visit_route') visit_route,
       json_value(jsonObj, N'$.attributes.keyword') keyword
from #json;

Output输出

id                                      source  medium  visit_route                                                                       keyword
51cf9ff0-0ed5-11eb-8887-53248e3b2424    Google  cpc     [{time_on_page": 5, "page_title": "Dedicated Servers" }, { "time_on_page": 1, "page_title": "Partner Programme" } ] NULL

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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