如何将复杂的 JSON 字符串放入 SQL Server 列中

Posted

技术标签:

【中文标题】如何将复杂的 JSON 字符串放入 SQL Server 列中【英文标题】:How to get complex JSON string into columns SQL Server 【发布时间】:2021-04-22 14:30:02 【问题描述】:

我已将一些数据作为 JSON 字符串存储在表中,如下所示。

[
   
      "firstName":"John",
      "lastName":"Smith",
      "age":25,
      "Address":
         "streetAddress":"21 2nd Street",
         "city":"New York",
         "state":"NY",
         "postalCode":"10021"
      ,
      "PhoneNumbers":
         "home":"212 555-1234",
         "fax":"646 555-4567"
      
   ,
   
      "firstName":"Mike",
      "lastName":"Lee",
      "age":30,
      "Address":
         "streetAddress":"10 Street",
         "city":"New York",
         "state":"NY",
         "postalCode":"10021"
      ,
      "PhoneNumbers":
         "home":"212 555-3265",
         "fax":""
      
   
]

要将这些数据导出到 excel 文件,我需要进行查询以获取这些详细信息,如下所示

使用 CROSS APPLY OPENJSON 我可以获取姓名和年龄,但如何获取地址和联系方式作为列?

【问题讨论】:

【参考方案1】:

您需要使用OPENJSON() 和相应的paths:

JSON:

DECLARE @json nvarchar(max) = N'[
   
      "firstName":"John",
      "lastName":"Smith",
      "age":25,
      "Address":
         "streetAddress":"21 2nd Street",
         "city":"New York",
         "state":"NY",
         "postalCode":"10021"
      ,
      "PhoneNumbers":
         "home":"212 555-1234",
         "fax":"646 555-4567"
      
   ,
   
      "firstName":"Mike",
      "lastName":"Lee",
      "age":30,
      "Address":
         "streetAddress":"10 Street",
         "city":"New York",
         "state":"NY",
         "postalCode":"10021"
      ,
      "PhoneNumbers":
         "home":"212 555-3265",
         "fax":""
      
   
]'

声明:

SELECT *
FROM OPENJSON(@json) WITH (
   FirstName nvarchar(100) '$.firstName',
   LastName nvarchar(100) '$.lastName',
   Age int '$.age',
   Name nvarchar(100) '$.firstName',
   StreetAddress nvarchar(100) '$.Address.streetAddress',
   City nvarchar(100) '$.Address.city',
   State nvarchar(100) '$.Address.state',
   PostalCode nvarchar(100) '$.Address.postalCode',
   HomePhone nvarchar(100) '$.PhoneNumbers.home',
   Fax nvarchar(100) '$.PhoneNumbers.fax'
)

结果:

FirstName LastName Age Name StreetAddress City     State PostalCode HomePhone    Fax
John      Smith     25 John 21 2nd Street New York NY    10021      212 555-1234 646 555-4567
Mike      Lee       30 Mike 10 Street     New York NY    10021      212 555-3265    

【讨论】:

谢谢。我很接近,只是缺少 Address.postalCode 的东西。 :)

以上是关于如何将复杂的 JSON 字符串放入 SQL Server 列中的主要内容,如果未能解决你的问题,请参考以下文章

如何将空字符串放入 JSON_OBJECT_T 对象?

kettle调用一个web service 如何将返回的json字符串解析并放入数据表中

如何从 Scala Json 字符串中将 Json 放入 JS 变量中?

如何从 JSON 字符串中删除括号和引号

将 PHP SQL 转换为 Laravel 查询构建器 [重复]

如何正确使用javascript反序列化将json字符串转换为复杂对象?