使用TSQL查询和更新 JSON 数据

本文涉及的产品
云数据库 RDS SQL Server,独享型 2核4GB
简介:

JSON是一个非常流行的,用于数据交换的文本数据(textual data)格式,主要用于Web和移动应用程序中。JSON 使用“键/值对”(Key:Value pair)存储数据,能够表示嵌套键值对和数组两种复杂数据类型,JSON仅仅使用逗号(引用Key)和中括号(引用数组元素),就能路由到指定的属性或成员,使用简单,功能强大。在SQL Server 2016版本中支持JSON格式,使用Unicode字符类型表示JSON数据,并能对JSON数据进行验证,查询和修改。推荐一款JSON验证和格式化的在线工具:json formatter

SQL Server 提供了内置函数,用于查询和更新JSON数据,分析JSON文本,如图:

一,定义和验证JSON数据

使用nvarchar存储JSON文本数据,通过函数 ISJSON(expression) 验证JSON数据是否有效。

复制代码
declare @json nvarchar(max)
set @json = 
N'{
    "info":{  
      "type":1,
      "address":{  
        "town":"bristol",
        "county":"avon",
        "country":"england"
      },
      "tags":["sport", "water polo"]
   },
   "type":"basic"
}'

select isjson(@json)
复制代码

ISJSON 函数的格式是: ISJSON ( expression ) ,返回1,表示字符串是JSON数据;返回0,表示字符串不是JSON数据;返回NULL,表示 expression是NULL;

二,JSON 数据的PATH 表达式

Path 表达式分为两部分:Path Mode和Path,Path Mode是可选的(optional),有两种模式:lax和strict。

1,Path Mode

在Path 表达式的开始,可以通过lax 或 strict 关键字显式声明Path Mode,如果不声明,默认的Path Mode是lax。在lax 模式下,如果path表达式出错,那么JSON函数返回NULL。在strict模式下,如果Path表达式出错,那么JSON函数抛出错误;

2,Path 表达式

Path是访问JSON数据的途径,有四种运算符:

  • $:代表整个JSON 数据的内容;
  • 逗号 . :表示JSON对象的成员,也叫做,字段(Field),或Key;
  • 中括号 [] :表示数组中的元素,元素的起始位置是0;
  • Key Name:键的名字,通过Key Name引用对应的Value;如果Key Name中包含空格,$,逗号,中括号,使用双引号;

例如,有如下JSON 数据,通过Path表达式,能够路由到JSON的各个属性:

复制代码
{ "people":  
  [  
    { "name": "John", "surname": "Doe" },  
    { "name": "Jane", "surname": null, "active": true }  
  ]  
} 
复制代码

Path表达式查询的数据是:

  • $:表示JSON的内容,是最外层大括号中的所有Item,本例是一个people数组,数组的下标是从0开始的;
  • $.people[0]:表示people数组的第一元素:{ "name": "Jane", "surname": null, "active": true }
  • $.people[0].name :从people数组的第一个元素中,查询Key是Name的Item对应的数据,本例是John;
  • $.people[1].surname:people数组中部存在surname 字段,由于该Path 表达式没有声明Path Mode,默认值是lax,当Path表达式出现错误时,返回NULL;

三,通过Path查询JSON数据

1,查询标量值(JSON_VALUE)

使用 JSON_VALUE(expression , path ) 函数,从JSON数据,根据Path 参数返回标量值,返回的数据是宽字符类型,最大值Nvarchar(4000);如果必须返回大于nvarchar(4000)的数据,使用OpenJson行集函数。

复制代码
declare @json nvarchar(max)
set @json = 
N'{
    "info":{  
      "type":1,
      "address":{  
        "town":"bristol",
        "county":"avon",
        "country":"england"
      },
      "tags":["sport", "water polo"]
   },
   "type":"basic"
}'

select
  json_value(@json, '$.type') as type,
  json_value(@json, '$.info.type') as info_type,
  json_value(@json, '$.info.address.town') as town,
  json_value(@json, '$.info.tags[0]') as tag
复制代码

2,返回JSON数据(JSON_QUERY)

使用 JSON_QUERY ( expression [ , path ] ) 函数,根据Path 参数,返回JSON 数据(JSON fragment);参数path是可选的(optional),如果不指定option参数,那么默认的path是$,即,返回整个JSON数据。

复制代码
declare @json nvarchar(max)
set @json = 
N'{
    "info":{  
      "type":1,
      "address":{  
        "town":"bristol",
        "county":"avon",
        "country":"england"
      },
      "tags":["sport", "water polo"]
   },
   "type":"basic"
}'

select
    json_query(@json, '$') as json_context,
    json_query(@json, '$.info') as info,
    json_query(@json, '$.info.address') as info_address,
    json_query(@json, '$.info.tags') as info_tags
复制代码

四,通过Path修改JSON数据

使用 JSON_MODIFY ( expression , path , newValue ) 修改JSON数据中的属性值,并返回修改之后的JSON数据,该函数修改JSON数据的流程是:

  • 修改现有的属性:按照参数path从JSON数据中找到指定的属性,将该属性的Value修改为参数newValue,返回值是修改之后的JSON数据;
  • 新增新的键值对(Key:Value pair):如果JSON数据中不存在指定的属性,那么按照参数Path,在指定的路径上新增键值对;
  • 删除键值对(Key:Value pair):如果参数newValue的值是NULL,那么表示从JSON数据中删除指定的属性;
  • append 关键字:用于从JSON数组中,追加一个元素;

示例,对JSON数据进行update,insert,delete和追加数据元素

复制代码
declare @info nvarchar(100) = '{"name":"john","skills":["c#","sql"]}'  
-- update name  
set @info = json_modify(@info, '$.name', 'mike')  
-- insert surname  
set @info = json_modify(@info, '$.surname', 'smith')  
-- delete name  
set @info = json_modify(@info, '$.name', null)  
-- add skill  
set @info = json_modify(@info, 'append $.skills', 'azure')  
复制代码

五,将JSON数据转换为关系表

OPENJSON函数是一个行集函数(RowSet),能够将JSON数据转换为关系表,

OPENJSON( jsonExpression [ , path ] )  
[  
   WITH (   
      colName type [ column_path ] [ AS JSON ]  
   [ , colName type [ column_path ] [ AS JSON ] ]  
   [ , . . . n ]   
      )  
] 
View Code
  • path 参数:也叫table path,指定关系表在JSON数据中的路径;
  • column_path 参数:基于path参数,指定每个column在关系表JSON中的路径,应总是显式指定column path;
  • AS JSON 属性:如果指定AS JSON属性,那么 column的数据类型必须定义为nvarchar(max),表示该column的值是JSON数据;如果不指定AS JSON属性,那么该Column的值是标量值;
  • with 选项:指定关系表的Schema,应总是指定with选项;如果不指定with 选项,那么函数返回key,value和type三列;

1,示例,从JSON数据中,以关系表方式呈现数据

复制代码
declare @json nvarchar(max)
set @json = 
N'{
    "info":{  
      "type":1,
      "address":{  
        "town":"bristol",
        "county":"avon",
        "country":"england"
      },
      "tags":["sport", "water polo"]
   },
   "type":"basic"
}'

SELECT info_type,info_address,tags
FROM OPENJSON(@json, '$.info') 
with 
(
info_type tinyint 'lax $.type',
info_address nvarchar(max) 'lax $.address' as json,
tags nvarchar(max) 'lax $.tags' as json
)
复制代码

2,OpenJSON 函数的另外一个功能是遍历数组,为数组中的每一个元素产生一个数据行

When you use OPENJSON with an explicit schema, the function returns a table with the schema that you defined in the WITH clause. In the WITH clause, you define columns, their types, and the paths of the source properties for each column.

  • For each element in the array in the input expression, OPENJSON generates a separate row in the output table.

  • For each property of the array elements specified by using the colName type column_path syntax, OPENJSON converts the value to the specified type and populates a cell in the output table.

SET @json = N'{"Orders":   
  {"OrdersArray":  
    [  
      {  
        "Order": {  
          "Number":"SO43659",  
          "Date":"2011-05-31T00:00:00"  
        },  
        "AccountNumber":"AW29825",  
        "Item": {  
          "Price":2024.9940,  
          "Quantity":1  
        }  
      },  
      {  
        "Order": {  
          "Number":"SO43661",  
          "Date":"2011-06-01T00:00:00"  
        },  
        "AccountNumber":"AW73565",  
        "Item": {  
          "Price":2024.9940,  
          "Quantity":3  
        }  
      }  
    ]  
  }  
}'  
  
SELECT t.* 
FROM  
OPENJSON ( @json, '$.Orders.OrdersArray' )  
WITH (   
             Number   varchar(200)   '$.Order.Number',  
             Date     datetime       '$.Order.Date',  
             Customer varchar(200)   '$.AccountNumber',  
             Quantity int            '$.Item.Quantity',  
             [Order]  nvarchar(MAX)  AS JSON  
) as t
View Code

3,OpenJSON 函数搭配Apply使用,为表中的JSON数据转换成关系表形式

select t.*,sl.result,sl.time
from [dbo].[WebPages] sl 
cross apply openjson(JSON_QUERY(Parameters,'$.CategoryList'))
with
(
    ID varchar(64) '$.ID',
    name varchar(64) '$.Name',
    Type varchar(64) '$.Type'
)
 as t
where sl.action='New Product' and t.Type in('Blogs','Forums')
order by sl.time desc
View Code

六,将关系表数据以JSON格式存储

通过For JSON  Auto/Path,将关系表数据存储为JSON格式,

  • Auto 模式:根据select语句中column的顺序,自动生成JSON数据的格式;
  • Path 模式:使用column name的格式来生成JSON数据的格式,column name使用逗号分隔(dot-separated)表示组-成员关系;

示例,有表:dt_json,存储以下数据:

1,以Auto 模式生成JSON格式

select id,
    name,
    category
from dbo.dt_json
for json auto,root('json')

返回的数据格式是

{  
   "json":[  
      {  
         "id":1,
         "name":"C#",
         "category":"Computer"
      },
      {  
         "id":2,
         "name":"English",
         "category":"Language"
      },
      {  
         "id":3,
         "name":"MSDN",
         "category":"Web"
      },
      {  
         "id":4,
         "name":"Blog",
         "category":"Forum"
      }
   ]
}
View Code

2,以Path模式生成JSON格式,推荐使用path模式,特别是在字段来源于多个表的情况下,控制JSON的格式

select id as 'book.id',
    name as 'book.name',
    category as 'product.category'
from dbo.dt_json
for json path,root('json')

返回的数据格式是:

{
"json":[
{
"book":{
"id":1,
"name":"C#"
},
"product":{
"category":"Computer"
}
},
{
"book":{
"id":2,
"name":"English"
},
"product":{
"category":"Language"
}
},
{
"book":{
"id":3,
"name":"MSDN"
},
"product":{
"category":"Web"
}
},
{
"book":{
"id":4,
"name":"Blog"
},
"product":{
"category":"Forum"
}
}
]
}
View Code

七,索引JSON数据

JSON文本不是内置的数据类型,没有专门的JSON索引,但是,可以通过创建计算列和标准B-Tree索引提高查询JSON数据的性能,避免全表扫描(Full Table Scan),通过索引计算列,间接实现对JSON进行查找。

索引JSON数据的Workaround是:为查询条件(Filter)创建计算列,使用persisted属性持久存储;在计算列上创建索引,使用包含列(Include)包含特定的字段,以避免键值查找(Key Lookup),提高索引查找的性能。

例如,有如下关系表,字段category包含JSON数据:

按照type属性过滤,包含name字段,创建索引的示例是:

复制代码
alter table dbo.dt_json
add category_type as (cast(json_value(category,'$.type') as int)) persisted;

create nonclustered index idx_dt_json_category_type
on dbo.dt_json
(
category_type
)
include(name);
复制代码

八,JSON查询技巧

1,使用Path模式,控制JSON结构的Path(层次)

当字段来源于多个Table时,使用Auto模式,在SQL Server 2016中,默认会将字段分组,

复制代码
select top 3 t.name
    ,o.object_id
    ,o.type
from sys.objects o 
inner join sys.tables t 
    on o.object_id=t.object_id
for json auto
复制代码

返回的结果是,多了一个层次:

[{"name":"table_1","o":[{"object_id":27147142,"type":"U "}]},
{"name":"table_2","o":[{"object_id":87671360,"type":"U "}]},
{"name":"table_3","o":[{"object_id":91147370,"type":"U "}]}]

使用Path模式(for json path),path是根据列的别名来定义Json的层次

[{"name":"table_1","object_id":27147142,"type":"U "},
{"name":"table_2","object_id":87671360,"type":"U "},
{"name":"table_3","object_id":91147370,"type":"U "}
]

2,嵌套JSON结构

在查询时,Table_2的JsonData字段是个Json数据,需要嵌套到另一个JSON中,例如:[{"UnitPrice":12, "OrderQty":1}],如果在外层JSON结构中,嵌套一个内层的JSON结构:

复制代码
select t1.ID
    ,t2.JsonData
from dbo.table_1 t1
inner join dbo.table_2 t2
    on ...
for json path
复制代码

返回的数据如下,JsonData是一个字符串,SQL Server自动对其进行字符转码:

复制代码
[
  {
    "Id": 12,
    "JsonData": "[{\"UnitPrice\":12, \"OrderQty\":1}]"
  }
]
复制代码

在嵌套的JSON上,使用JSON_Query(expression,path),返回数据,然后再对其进行JSON 格式:

复制代码
select t1.ID
    ,json_query(t2.JsonData) as JsonData
from dbo.table_1 t1
inner join dbo.table_2 t2
    on ...
for json path
复制代码

返回的JSON结构如下,满足:

复制代码
[
  {
    "Id": 12,
    "JsonData": [{"UnitPrice":12, "OrderQty":1}]
  }
]
复制代码

 

九,编程注意事项

1,空JSON

JSON_QUERY(expression,path) 要求expression必须是有效的,为避免JSON_QUERY执行失败,对NULL值,要么保持NULL值,要么设置空JSON,而空JSONO是 [] 或  {},而不是空的字符。

2,JSON中的数组

在查询时,经常会返回JSON数组,使用[index]来遍历数组元素,数组下标从0开始,例如,以下JSON数组,及其查询示例:

[
{...}
]
--path expression
lax $[0]

使用for json返回JSON时,可以去掉外层的数组包装器 [],例如

for json path,without_array_wrapper

 

 

 

参考文档:

JSON Data (SQL Server)

JSON Path Expressions (SQL Server)

JSON Functions (Transact-SQL)

OPENJSON (Transact-SQL)

Index JSON data

Format Query Results as JSON with FOR JSON (SQL Server)

Format Nested JSON Output with PATH Mode (SQL Server)

Format JSON Output Automatically with AUTO Mode (SQL Server)

JSON Support in SQL Server 2016

JSON in SQL Server 2016: Part 1 of 4

作者悦光阴
本文版权归作者和博客园所有,欢迎转载,但未经作者同意,必须保留此段声明,且在文章页面醒目位置显示原文连接,否则保留追究法律责任的权利。
分类: SQL Server
标签: TSQL, JSON





本文转自悦光阴博客园博客,原文链接:http://www.cnblogs.com/ljhdo/p/4549152.html,如需转载请自行联系原作者
相关实践学习
使用SQL语句管理索引
本次实验主要介绍如何在RDS-SQLServer数据库中,使用SQL语句管理索引。
SQL Server on Linux入门教程
SQL Server数据库一直只提供Windows下的版本。2016年微软宣布推出可运行在Linux系统下的SQL Server数据库,该版本目前还是早期预览版本。本课程主要介绍SQLServer On Linux的基本知识。 相关的阿里云产品:云数据库RDS SQL Server版 RDS SQL Server不仅拥有高可用架构和任意时间点的数据恢复功能,强力支撑各种企业应用,同时也包含了微软的License费用,减少额外支出。 了解产品详情: https://www.aliyun.com/product/rds/sqlserver
目录
相关文章
|
1月前
|
存储 JSON Apache
揭秘 Variant 数据类型:灵活应对半结构化数据,JSON查询提速超 8 倍,存储空间节省 65%
在最新发布的阿里云数据库 SelectDB 的内核 Apache Doris 2.1 新版本中,我们引入了全新的数据类型 Variant,对半结构化数据分析能力进行了全面增强。无需提前在表结构中定义具体的列,彻底改变了 Doris 过去基于 String、JSONB 等行存类型的存储和查询方式。
揭秘 Variant 数据类型:灵活应对半结构化数据,JSON查询提速超 8 倍,存储空间节省 65%
|
2月前
|
XML 机器学习/深度学习 JSON
在火狐浏览器调ajax获取json数据时,控制台提示“XML 解析错误:格式不佳”。
在火狐浏览器调ajax获取json数据时,控制台提示“XML 解析错误:格式不佳”。
29 0
在火狐浏览器调ajax获取json数据时,控制台提示“XML 解析错误:格式不佳”。
|
11天前
|
存储 JSON JavaScript
「Python系列」Python JSON数据解析
在Python中解析JSON数据通常使用`json`模块。`json`模块提供了将JSON格式的数据转换为Python对象(如列表、字典等)以及将Python对象转换为JSON格式的数据的方法。
27 0
|
15天前
|
存储 JSON 数据挖掘
python逐行读取txt文本中的json数据,并进行处理
Python代码示例演示了如何读取txt文件中的JSON数据并处理。首先,逐行打开文件,然后使用`json.loads()`解析每一行。接着,处理JSON数据,如打印特定字段`name`。异常处理包括捕获`JSONDecodeError`和`KeyError`,确保数据有效性和字段完整性。将`data.txt`替换为实际文件路径运行示例。
12 2
|
1月前
|
JSON 数据格式
糊涂工具类(hutool)post请求设置body参数为json数据
糊涂工具类(hutool)post请求设置body参数为json数据
30 1
|
1月前
|
JSON 前端开发 数据格式
Ajax传递json数据
Ajax传递json数据
11 0
|
1月前
|
JSON 并行计算 API
使用CJSON/Nlohmann:快速简便地在C/C++中处理JSON数据
使用CJSON/Nlohmann:快速简便地在C/C++中处理JSON数据
111 0
|
1月前
|
JSON 数据格式 Python
Python生成JSON数据
Python生成JSON数据
23 0
|
1月前
|
JSON 数据可视化 Linux
数据可视化工具JSON Crack结合内网穿透实现公网访问
数据可视化工具JSON Crack结合内网穿透实现公网访问
数据可视化工具JSON Crack结合内网穿透实现公网访问
|
2月前
|
JSON fastjson Java
FastJSON操作各种格式的JSON数据
FastJSON处理各种格式的JSON数据