How to read field name with space in Json using OPENJSON in SQL Server 2016

不羁的心 提交于 2020-08-20 03:59:35

问题


How can I read value from json file in that field name contains space using OPENJSON in Sql Server 2016. See the below code:

DECLARE @json NVARCHAR(MAX)
SET @json = N'{ "full name" : "Jayesh Tank"}';
SELECT * FROM OPENJSON(@json) WITH ( [name] [varchar](60) '$.full name')

Also another sample code in that space is after field name.

SET @json = N'{ "name   " : "abc"}';
SELECT * FROM OPENJSON(@json) WITH ( [name] [varchar](60)    '$.name')

'$.name' will return null.Is there way to read this value?


回答1:


Generally it is a bad idea to use spaces in the attribute name.

I would leave out the [ ] from your OPENJSON name and varchar(60) - source MSDN OPENJSON.

Now to actually answer your question:

You need to format your attribute with double quotes in the WITH clause:

@DECLARE @json NVARCHAR(MAX);
SET @json=N'{ "full name" : "Jayesh Tank"}';
SELECT * FROM OPENJSON(@json) WITH (name varchar(60) '$."full name"')

for the second one:

SET @json = N'{ "name   " : "abc"}';
SELECT * FROM OPENJSON(@json) WITH ( name varchar(60)'$."name   "')


来源:https://stackoverflow.com/questions/45345458/how-to-read-field-name-with-space-in-json-using-openjson-in-sql-server-2016

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!