简体   繁体   English

SQL 查询Json object inside Json

[英]SQL Query for Json object inside Json

I have the below Json string.我有以下 Json 字符串。 I need to write a query to get the SP records.我需要编写一个查询来获取 SP 记录。 Without providing the index value, we need get the result.在不提供索引值的情况下,我们需要得到结果。

 {
   "S": [
    {
      "Name": "Project1",
       "SP": [
        {
          "ID": 1,
          "Name": "Test1"
        },
        {
          "ID": 2,
          "Name": "Test2"
        },
  }]}

How do I query to get the SP values.如何查询以获取 SP 值。

Expected Result:

 ID    Name 
 1     Test1 
 2     Test2

 I tried the below but not working. Can you please suggest the correct query.

SELECT DISTINCT JSON_VALUE(JsonData, '$.S[0].SP.ID') AS ID,
                JSON_VALUE(JsonData, '$.S[0].SP.Name') AS Name
    FROM TableA

You can use JSON_QUERY nested in OPENJSON function containing WITH Clause in order to visit all members of SP array dynamically:您可以使用嵌套在包含WITH子句的JSON_QUERY function 中的OPENJSON来动态访问SP数组的所有成员:

SELECT ID, Name
  FROM TableA
 CROSS APPLY OPENJSON(JSON_QUERY(JsonData, '$.S[0].SP'))
             WITH (ID   nvarchar(500) '$.ID',
                   Name nvarchar(500) '$.Name')

Btw, you need to fix the JsonData as converting to顺便说一句,您需要将 JsonData 修复为转换为

{
   "S": [
    {
      "Name": "0219 Project Methodology - Allergies",
       "SP": [
        {
          "ID": 1,
          "Name": "Test1"
        },
        {
          "ID": 2,
          "Name": "Test2"
        }
  ] } ] }

Demo 演示

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

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