如何从 SQL 服务器中的 JSON 获取每个对象的值

how to get the values of the each object from the JSON in SQL SERVER

DECLARE @json NVARCHAR(1000);
            
    SELECT @json = N'
       {
        "nodeinid": 1345,
        "data": [
          {
            "nodenametext": "Plan for project",
            "nodedesctext": "plan description for execution",
            "nodetypecode": "PLN",
            "statuscode": "IP",
            "prioritycode": "NI",
            "linkeditemid": 0,
            "linkeditemtypecode": "TSK",
            "startdttm": "2021-07-15T09:53:47.9575771",
            "duedttm": "2021-07-15T09:53:47.9575771",
            "hidefromclientindc": "true",
            "draftindc": "no",
            "inworkspaceid": 5678,
            "parentnodeid": 0,
            "categorytext": [
              {
                "categoryid": 111,
                "categoryidname": "college"
              },
              {
                "categoryid": 222,
                "categoryidname": "office"
              }
            ],
            "assigntotext": [
              {
                "workspaceid": 567,
                "roleid": 4545,
                "accesstypecode": "ass",
                "mailurl": "saram@gmail"
              },
              {
                "workspaceid": 977,
                "roleid": 67,
                "accesstypecode": "ass",
                "mailurl": "sarfdam@gmail"
              }
            ]
          }
        ]
      }
    ';

使用的查询:

    SELECT JSON_Value (c.value, '$.nodeinid') as nodein_id 
       ,JSON_Value (P.Value, '$.workspaceid') as workspace_id
     , JSON_Value (p.value, '$.accesstypecode') as accesstype_code
     , JSON_Value (Q.value, '$.categoryid') as category_id
     , JSON_Value (Q.value, '$.categoryidname') as categoryid_name
      
    FROM OPENJSON (@json, '$.data') as C
    CROSS APPLY OPENJSON (C.Value, '$.assigntotext') as P
    CROSS APPLY OPENJSON (C.Value, '$.categorytext') as Q;

预期样本输出:

workspace_id accesstype_code
567          ass
977          ass  

结果:查询抛出以下错误

Msg 13609, Level 16, State 4, Line 50
JSON text is not properly formatted. Unexpected character '"' is found at position 998.

如果我保留其中一个对象(assigntotext、categorytext)它工作正常。
请更正查询以获取行和列格式的值。"

好像是nvarchar(1000)不够用,输入的JSON被截断了。将 @json 变量的数据类型更改为 nvarchar(max)。您也可以尝试使用以下方法解析输入 JSON:

DECLARE @json NVARCHAR(max);
SELECT @json = N'... JSON data ...' 

SELECT j2.*
FROM OPENJSON(@json, '$.data') WITH (
   assigntotext nvarchar(max) '$.assigntotext' AS JSON
) j1
OUTER APPLY OPENJSON(j1.assigntotext) WITH (
   workspace_id int '$.workspaceid',
   accesstype_code varchar(10) '$.accesstypecode'
) j2

结果:

workspace_id accesstype_code
----------------------------
567          ass
977          ass