如果你一直使用json_modify()函数来修改sql server中的json文档,那么你可能习惯于修改key/value属性的value部分。但是你知道你也可以修改key部分吗?
这样做的诀窍是将value复制到一个新键,然后删除旧键。
这里有一个基本的例子来说明我的意思。
-- declare a variable and assign some json to itdeclare @data nvarchar(50)='{"name":"homer"}'-- print the current jsonprint @data-- rename the key (by copying the value to a new key, then deleting the old one)set @data= json_modify( json_modify(@data,'$.handle', json_value(@data,'$.name')), '$.name', null )-- print the new jsonprint @data
结果:
{"name":"homer"}{"handle":"homer"}
这将打印出原始的键/值对,然后是新的键/值对。
虽然我们可以说我们“重命名”了密钥,但实际上我们只是创建了一个新密钥,将现有值复制到该新密钥,然后将旧密钥设置为null来删除它。
在本例中,我们使用json_value()函数来提取值。
数值
在将数据复制到新键时需要小心。默认情况下,sql server将它括在双引号中。这可能是你想要的,也可能不是。
但是,如果你复制一个数值,你可能希望它仍然是一个数值(即没有双引号)。在本例中,需要使用cast()函数将其转换为数值数据类型。这里有一个例子:
-- declare a variable and assign some json to itdeclare @data nvarchar(50)='{"residents":768}'-- print the current jsonprint @data-- rename the key (by copying the value to a new key, then deleting the old one)set @data= json_modify( json_modify(@data,'$.population', cast(json_value(@data,'$.residents') as int)), '$.residents', null )-- print the new jsonprint @data
结果:
{"residents":768}{"population":768}
所以结果是一个数字。
如果我们从这个例子中删除cast()函数,我们得到的结果是:
-- declare a variable and assign some json to itdeclare @data nvarchar(50)='{"residents": 768}'-- print the current jsonprint @data-- rename the key (by copying the value to a new key, then deleting the old one)set @data= json_modify( json_modify(@data,'$.population', json_value(@data,'$.residents')), '$.residents', null )-- print the new jsonprint @data
结果:
{"residents": 768}{"population":"768"}
因此,在本例中,我们不仅重命名了键,还将(json)数据类型从数字更改为字符串。
注意,json不区分不同的数字类型。它只有一个数字类型:number。
key键和空格
在本例中,我将一个现有键重命名为一个包含空格的新键(它由两个单词组成,用空格分隔)。
因为新键包含空格,所以我需要用双引号括住键。如果不这样做,就会出现错误。
-- declare a variable and assign some json to itdeclare @data nvarchar(50)='{"population":68}'-- print the current jsonprint @data-- rename the key (by copying the value to a new key, then deleting the old one)set @data= json_modify( json_modify(@data,'$."average iq"', cast(json_value(@data,'$.population') as int)), '$.population', null )-- print the new jsonprint @data
结果:
{"population":68}{"average iq":68}
嵌套的属性
如果属性是嵌套的,则没有问题。只需使用点符号来引用它。
declare @data nvarchar(4000)set @data=n'{ "suspect": { "name": "homer simpson", "hobbies": ["eating", "sleeping", "base jumping"] } }'print @dataset @data= json_modify( json_modify(@data,'$.suspect.qualifications', json_query(@data,'$.suspect.hobbies')), '$.suspect.hobbies', null )print @data
结果:
{ "suspect": { "name": "homer simpson", "hobbies": ["eating", "sleeping", "base jumping"] }}{ "suspect": { "name": "homer simpson" ,"qualifications":["eating", "sleeping", "base jumping"]}}
你可能还注意到,这个示例使用json_query()函数来提取值,而不是像前面的示例那样使用json_value()。
这是因为在本例中,我们正在提取一个数组,而json_value()不能提取整个数组(它只能从数组中提取标量值)。另一方面,json_query()函数提取对象和数组,但不提取标量值。
相关推荐:《sql教程》《mysql教程》
以上就是如何在sql server中重命名json密钥(t-sql)?的详细内容。