如何从JSON字符串中读取具有长值的属性?

时间:2017-07-11 03:37:07

标签: sql sql-server json tsql sql-server-2016

我有一个JSON对象,其中一个属性具有很长的值。当我尝试使用JSON_VALUE()提取此值时,它将返回null。

declare @json nvarchar(max) =
'
{
    "AVeryLongValue": "Founded in 2008, Stack Overflow is the largest, most trusted online community for developers to learn, share their knowledge, and build their careers. More than 50 million professional and aspiring programmers visit Stack Overflow each month to help solve coding problems, develop new skills, and find job opportunities. Stack Overflow partners with businesses to help them understand, hire, engage, and enable the worlds developers. Our products and services are focused on developer marketing, technical recruiting, market research, and enterprise knowledge sharing. Learn more about our business solutions here. Founded in 2008, Stack Overflow is the largest, most trusted online community for developers to learn, share their knowledge, and build their careers. More than 50 million professional and aspiring programmers visit Stack Overflow each month to help solve coding problems, develop new skills, and find job opportunities. Stack Overflow partners with businesses to help them understand, hire, engage, and enable the worlds developers. Our products and services are focused on developer marketing, technical recruiting, market research, and enterprise knowledge sharing. Learn more about our business solutions here. Founded in 2008, Stack Overflow is the largest, most trusted online community for developers to learn, share their knowledge, and build their careers. More than 50 million professional and aspiring programmers visit Stack Overflow each month to help solve coding problems, develop new skills, and find job opportunities. Stack Overflow partners with businesses to help them understand, hire, engage, and enable the worlds developers. Our products and services are focused on developer marketing, technical recruiting, market research, and enterprise knowledge sharing. Learn more about our business solutions here. Founded in 2008, Stack Overflow is the largest, most trusted online community for developers to learn, share their knowledge, and build their careers. More than 50 million professional and aspiring programmers visit Stack Overflow each month to help solve coding problems, develop new skills, and find job opportunities. Stack Overflow partners with businesses to help them understand, hire, engage, and enable the worlds developers. Our products and services are focused on developer marketing, technical recruiting, market research, and enterprise knowledge sharing. Learn more about our business solutions here. Founded in 2008, Stack Overflow is the largest, most trusted online community for developers to learn, share their knowledge, and build their careers. More than 50 million professional and aspiring programmers visit Stack Overflow each month to help solve coding problems, develop new skills, and find job opportunities. Stack Overflow partners with businesses to help them understand, hire, engage, and enable the worlds developers. Our products and services are focused on developer marketing, technical recruiting, market research, and enterprise knowledge sharing. Learn more about our business solutions here. Founded in 2008, Stack Overflow is the largest, most trusted online community for developers to learn, share their knowledge, and build their careers. More than 50 million professional and aspiring programmers visit Stack Overflow each month to help solve coding problems, develop new skills, and find job opportunities. Stack Overflow partners with businesses to help them understand, hire, engage, and enable the worlds developers. Our products and services are focused on developer marketing, technical recruiting, market research, and enterprise knowledge sharing. Learn more about our business solutions here. Founded in 2008, Stack Overflow is the largest, most trusted online community for developers to learn, share their knowledge, and build their careers. More than 50 million professional and aspiring programmers visit Stack Overflow each month to help solve coding problems, develop new skills, and find job opportunities. Stack Overflow partners with businesses to help them understand, hire, engage, and enable the worlds developers. Our products and services are focused on developer marketing, technical recruiting, market research, and enterprise knowledge sharing. Learn more about our business solutions here. Founded in 2008, Stack Overflow is the largest, most trusted online community for developers to learn, share their knowledge, and build their careers. More than 50 million professional and aspiring programmers visit Stack Overflow each month to help solve coding problems, develop new skills, and find job opportunities. Stack Overflow partners with businesses to help them understand, hire, engage, and enable the worlds developers. Our products and services are focused on developer marketing, technical recruiting, market research, and enterprise knowledge sharing. Learn more about our business solutions here."
}
'
select json_value(@json, '$.AVeryLongValue') as 'AVeryLongValue'

结果:

AVeryLongValue
--------
NULL

我确认使用is_json(@json),JSON有效。长值似乎没有任何特殊字符等。

如果我缩短了值,我确实得到了我期望的值,所以代码似乎没问题。例如:

declare @json nvarchar(max) = '
{
    "AVeryLongValue": "Founded in 2008"
}
'
select json_value(@json, '$.AVeryLongValue') as 'AVeryLongValue'

结果:

AVeryLongValue
------------
Founded in 2008

问题:

  1. 为什么在读取长值时会得到null?是否需要任何特殊处理?
  2. 我有多个JSON对象,包含此属性的长值和短值。有时也会完全丢失该属性,因此JSON_VALUE()将为这些对象返回null。任何建议如何仅对这个属性作为long值的对象应用条件特殊处理?

2 个答案:

答案 0 :(得分:2)

为什么在读取长值时会得到null?

因为该值超过4000个字符且json_value()无法处理它。这是MSDN reference

  

返回值

     

返回nvarchar(4000)类型的单个文本值。

     

如果值大于4000个字符:

In lax mode, JSON_VALUE returns null.

In strict mode, JSON_VALUE returns an error.

是否需要特殊处理?我如何解决这个限制?

发现了这段精彩视频SQL Server 2016 and JSON Support on Channel9,该视频于15:00提及此问题,建议在25:00解决此问题

select value from openjson(@json) where[key] = 'AVeryLongValue'

我有多个JSON对象,包含此属性的长值和短值。有时也会完全丢失该属性,因此JSON_VALUE()将为这些对象返回null。是否建议如何仅对此属性作为long值的对象应用条件特殊处理?

json_value()提供的JSON表达式中使用'strict' path mode,如果属性值很长并且会被截断,可能会使json_value()抛出错误。

declare @json nvarchar(max) =
'
{
    "AVeryLongValue": "Founded in 2008, Stack Overflow is the largest, most trusted online community for developers to learn, share their knowledge, and build their careers. More than 50 million professional and aspiring programmers visit Stack Overflow each month to help solve coding problems, develop new skills, and find job opportunities. Stack Overflow partners with businesses to help them understand, hire, engage, and enable the worlds developers. Our products and services are focused on developer marketing, technical recruiting, market research, and enterprise knowledge sharing. Learn more about our business solutions here. Founded in 2008, Stack Overflow is the largest, most trusted online community for developers to learn, share their knowledge, and build their careers. More than 50 million professional and aspiring programmers visit Stack Overflow each month to help solve coding problems, develop new skills, and find job opportunities. Stack Overflow partners with businesses to help them understand, hire, engage, and enable the worlds developers. Our products and services are focused on developer marketing, technical recruiting, market research, and enterprise knowledge sharing. Learn more about our business solutions here. Founded in 2008, Stack Overflow is the largest, most trusted online community for developers to learn, share their knowledge, and build their careers. More than 50 million professional and aspiring programmers visit Stack Overflow each month to help solve coding problems, develop new skills, and find job opportunities. Stack Overflow partners with businesses to help them understand, hire, engage, and enable the worlds developers. Our products and services are focused on developer marketing, technical recruiting, market research, and enterprise knowledge sharing. Learn more about our business solutions here. Founded in 2008, Stack Overflow is the largest, most trusted online community for developers to learn, share their knowledge, and build their careers. More than 50 million professional and aspiring programmers visit Stack Overflow each month to help solve coding problems, develop new skills, and find job opportunities. Stack Overflow partners with businesses to help them understand, hire, engage, and enable the worlds developers. Our products and services are focused on developer marketing, technical recruiting, market research, and enterprise knowledge sharing. Learn more about our business solutions here. Founded in 2008, Stack Overflow is the largest, most trusted online community for developers to learn, share their knowledge, and build their careers. More than 50 million professional and aspiring programmers visit Stack Overflow each month to help solve coding problems, develop new skills, and find job opportunities. Stack Overflow partners with businesses to help them understand, hire, engage, and enable the worlds developers. Our products and services are focused on developer marketing, technical recruiting, market research, and enterprise knowledge sharing. Learn more about our business solutions here. Founded in 2008, Stack Overflow is the largest, most trusted online community for developers to learn, share their knowledge, and build their careers. More than 50 million professional and aspiring programmers visit Stack Overflow each month to help solve coding problems, develop new skills, and find job opportunities. Stack Overflow partners with businesses to help them understand, hire, engage, and enable the worlds developers. Our products and services are focused on developer marketing, technical recruiting, market research, and enterprise knowledge sharing. Learn more about our business solutions here. Founded in 2008, Stack Overflow is the largest, most trusted online community for developers to learn, share their knowledge, and build their careers. More than 50 million professional and aspiring programmers visit Stack Overflow each month to help solve coding problems, develop new skills, and find job opportunities. Stack Overflow partners with businesses to help them understand, hire, engage, and enable the worlds developers. Our products and services are focused on developer marketing, technical recruiting, market research, and enterprise knowledge sharing. Learn more about our business solutions here. Founded in 2008, Stack Overflow is the largest, most trusted online community for developers to learn, share their knowledge, and build their careers. More than 50 million professional and aspiring programmers visit Stack Overflow each month to help solve coding problems, develop new skills, and find job opportunities. Stack Overflow partners with businesses to help them understand, hire, engage, and enable the worlds developers. Our products and services are focused on developer marketing, technical recruiting, market research, and enterprise knowledge sharing. Learn more about our business solutions here."
}
'
declare @AVeryLongValue nvarchar(max)
select @AVeryLongValue = json_value(@json, 'strict $.AVeryLongValue')

结果

Msg 13625, Level 16, State 1, Line 13
String value in the specified JSON path would be truncated.

此外,如果JSON中缺少该属性,则会导致如下错误:

Msg 13608, Level 16, State 5, Line 12
Property cannot be found on the specified JSON path.

我可以使用strict模式和try-catch这样的逻辑来处理对象的混合。

declare @json nvarchar(max) =
'
{
    "AVeryLongValue": "Founded in 2008, Stack Overflow is the largest, most trusted online community for developers to learn, share their knowledge, and build their careers. More than 50 million professional and aspiring programmers visit Stack Overflow each month to help solve coding problems, develop new skills, and find job opportunities. Stack Overflow partners with businesses to help them understand, hire, engage, and enable the worlds developers. Our products and services are focused on developer marketing, technical recruiting, market research, and enterprise knowledge sharing. Learn more about our business solutions here. Founded in 2008, Stack Overflow is the largest, most trusted online community for developers to learn, share their knowledge, and build their careers. More than 50 million professional and aspiring programmers visit Stack Overflow each month to help solve coding problems, develop new skills, and find job opportunities. Stack Overflow partners with businesses to help them understand, hire, engage, and enable the worlds developers. Our products and services are focused on developer marketing, technical recruiting, market research, and enterprise knowledge sharing. Learn more about our business solutions here. Founded in 2008, Stack Overflow is the largest, most trusted online community for developers to learn, share their knowledge, and build their careers. More than 50 million professional and aspiring programmers visit Stack Overflow each month to help solve coding problems, develop new skills, and find job opportunities. Stack Overflow partners with businesses to help them understand, hire, engage, and enable the worlds developers. Our products and services are focused on developer marketing, technical recruiting, market research, and enterprise knowledge sharing. Learn more about our business solutions here. Founded in 2008, Stack Overflow is the largest, most trusted online community for developers to learn, share their knowledge, and build their careers. More than 50 million professional and aspiring programmers visit Stack Overflow each month to help solve coding problems, develop new skills, and find job opportunities. Stack Overflow partners with businesses to help them understand, hire, engage, and enable the worlds developers. Our products and services are focused on developer marketing, technical recruiting, market research, and enterprise knowledge sharing. Learn more about our business solutions here. Founded in 2008, Stack Overflow is the largest, most trusted online community for developers to learn, share their knowledge, and build their careers. More than 50 million professional and aspiring programmers visit Stack Overflow each month to help solve coding problems, develop new skills, and find job opportunities. Stack Overflow partners with businesses to help them understand, hire, engage, and enable the worlds developers. Our products and services are focused on developer marketing, technical recruiting, market research, and enterprise knowledge sharing. Learn more about our business solutions here. Founded in 2008, Stack Overflow is the largest, most trusted online community for developers to learn, share their knowledge, and build their careers. More than 50 million professional and aspiring programmers visit Stack Overflow each month to help solve coding problems, develop new skills, and find job opportunities. Stack Overflow partners with businesses to help them understand, hire, engage, and enable the worlds developers. Our products and services are focused on developer marketing, technical recruiting, market research, and enterprise knowledge sharing. Learn more about our business solutions here. Founded in 2008, Stack Overflow is the largest, most trusted online community for developers to learn, share their knowledge, and build their careers. More than 50 million professional and aspiring programmers visit Stack Overflow each month to help solve coding problems, develop new skills, and find job opportunities. Stack Overflow partners with businesses to help them understand, hire, engage, and enable the worlds developers. Our products and services are focused on developer marketing, technical recruiting, market research, and enterprise knowledge sharing. Learn more about our business solutions here. Founded in 2008, Stack Overflow is the largest, most trusted online community for developers to learn, share their knowledge, and build their careers. More than 50 million professional and aspiring programmers visit Stack Overflow each month to help solve coding problems, develop new skills, and find job opportunities. Stack Overflow partners with businesses to help them understand, hire, engage, and enable the worlds developers. Our products and services are focused on developer marketing, technical recruiting, market research, and enterprise knowledge sharing. Learn more about our business solutions here."
}
'

declare @AVeryLongValue nvarchar(max)
begin try
    select @AVeryLongValue = json_value(@json, 'strict $.AVeryLongValue') 
end try
begin catch
    select 'In catch section'
    select  @AVeryLongValue = value from openjson(@json) where[key] = 'AVeryLongValue'
end catch
if @AVeryLongValue is null
    select 'The JSON did not have property AVeryLongValue'
else
    select @AVeryLongValue

答案 1 :(得分:1)

我可能找到了一种管理大于JSON_Value nvarchar (4000)的值的方法。

使用 WITH 子句:

DECLARE @jsonInfo NVARCHAR(MAX)
SET @jsonInfo=N'{
    "Items": [ {
            "guid": "f0acb160-62eb-4622-bef2-bb9e8afe7314",
            "timestamp": "2017-10-31T23:59:51.093Z",
            "data": {
                "LongText": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas venenatis vel orci a tincidunt. Maecenas suscipit sed neque non mollis. Proin nec mollis lacus, in gravida lorem. Nullam pharetra urna vitae consectetur placerat. Proin rutrum risus vitae nunc mattis, nec pellentesque ligula viverra. Maecenas at semper libero. Curabitur porta urna vel arcu interdum scelerisque. Cras ultrices tincidunt pulvinar. Nam molestie aliquet sapien nec ultricies. Nulla facilisis quam a ante lobortis tincidunt. Morbi ac nulla mi.Morbi mattis in ex non ullamcorper. Etiam sit amet lacus eros. Suspendisse ac magna purus. Quisque vel lectus a libero posuere condimentum ac posuere orci. Fusce vel molestie velit. Nunc vulputate mauris consequat massa imperdiet, in aliquet metus dignissim. Donec posuere odio suscipit, sollicitudin tellus nec, ultricies augue. Duis vel lacinia massa. Nam venenatis mauris ut risus pharetra bibendum. Phasellus ornare enim eu enim mattis efficitur. Cras in arcu leo. Maecenas nec tempus mauris. Nulla vel tortor non elit elementum maximus. Nulla eu ex neque. Duis nisi odio, finibus a dui vel, sodales venenatis leo. Pellentesque fermentum rutrum pellentesque.Nullam euismod nulla lectus, a blandit nisi viverra non. Aliquam ut auctor turpis. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Vestibulum id ante scelerisque, aliquet ipsum interdum, dapibus diam. Fusce faucibus orci ut eros aliquet finibus. Maecenas magna turpis, pulvinar a eleifend sed, gravida eget massa. Praesent laoreet convallis condimentum. Aenean rutrum leo id malesuada fermentum. Nullam quis ullamcorper ipsum, non imperdiet mi. Cras ex neque, molestie maximus rutrum sit amet, rhoncus quis justo. Cras venenatis consequat justo sed cursus. Phasellus mollis malesuada interdum. Aliquam erat volutpat. Curabitur ultricies dapibus ante sit amet convallis.Quisque massa mi, mattis sed semper eu, rutrum ut massa. Nam velit enim, placerat id placerat et, aliquam vel purus. Nulla non auctor eros. Nullam sed elit metus. Donec tempor tempus sagittis. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nunc elementum gravida auctor. Aenean posuere pretium consequat.Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. In eu finibus ligula, a blandit felis. Cras interdum sapien ac urna fringilla ornare. In consequat lectus luctus tellus tempus pellentesque. Duis vitae turpis tincidunt, tincidunt mauris at, vehicula ligula. Curabitur sed tortor lacinia sapien varius tincidunt vitae nec est. Duis pulvinar eros lorem, id luctus justo convallis tempor. Pellentesque sit amet eros a magna condimentum hendrerit non vitae enim.Pellentesque sit amet ex vel felis auctor luctus ultricies ac mauris. Vivamus tempus sit amet ipsum vitae hendrerit. Vivamus dignissim blandit magna tempor pharetra. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nam tempus tristique justo egestas tempor. Nulla lacus tortor, interdum ac ante pulvinar, ultricies mollis ligula. Donec facilisis blandit justo, ac vulputate urna tempor vel. Curabitur commodo ex et fringilla pellentesque. Donec lobortis lorem vel ante rhoncus posuere. Suspendisse cursus velit sit amet nisi sagittis tristique. Ut nec accumsan risus, id tincidunt ipsum. Vivamus convallis sodales tellus vel ultricies.Nam semper risus ligula, eu venenatis ipsum fringilla quis. Sed cursus pellentesque ex eu finibus. Morbi ligula lectus, semper et laoreet id, porttitor quis sapien. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nulla a feugiat est, vel faucibus arcu. Vivamus molestie tortor a augue maximus vulputate. Aliquam at nulla nibh. Nullam blandit quam sed tortor gravida, nec scelerisque felis interdum.Cras et interdum elit, quis laoreet sapien. Integer arcu dui, interdum eu egestas placerat, posuere a posuere."
            }
        }
    ]
}'

-- doesnt work because of the JSON_Value nvarchar (4000)
 SELECT 
 JSON_Value (i.value, '$.guid') as [GUID],
  CONVERT(datetime, JSON_Value (i.value, '$.timestamp')) as [TimeStamp],
  JSON_Value (i.value, '$.data.LongText') as LongText
FROM OPENJSON (@jsonInfo, '$.Items') as i

-- workaround
select 
i.*
FROM OPENJSON (@jsonInfo, '$.Items')
WITH ([GUID]   nvarchar(40) '$.guid' , 
    [TimeStamp]   Datetime '$.timestamp',  
      LongText nvarchar(MAX) '$.data.LongText'
 )   as i

Result

默认情况下,我认为最好使用 WITH 子句,在Sql服务器博客上,据说它有更好的性能。 Blog Post