简体   繁体   中英

Sql server column serialization without key

I have column A with value hello .

I need to migrate it into new column AJson with value ["hello"] .

I have to do this with Sql Server command.

There are different commands FOR JSON etc. but they serialize value with column name.

This is the same value that C# method JsonConvert.SerializeObject(new List<string>(){"hello"} serialization result would be.

I can't simply attach [" in the beginning and end because the string value may contain characters which without proper serialization will break the json string.

My advice is you just make a lot of nested replaces and then do it yourself.

FOR JSON is intended for entire JSON, and therefore not valid without keys.

Here is a simple example that replaces the endline with \n

print replace('ab
c','
','\n')

Backspace to be replaced with \b.

Form feed to be replaced with \f.

Newline to be replaced with \n.

Carriage return to be replaced with \r.

Tab to be replaced with \t.

Double quote to be replaced with "

Backslash to be replaced with \

My approach was to use these 3 commands:

UPDATE Offers
SET [DetailsJson] =
      (SELECT TOP 1 [Details] AS A
       FROM Offers AS B
       WHERE B.Id = Offers.Id
       FOR JSON PATH, WITHOUT_ARRAY_WRAPPER)

UPDATE Offers
SET [DetailsJson] = Substring([DetailsJson], 6, LEN([DetailsJson]) - 6)

UPDATE Offers
SET [DetailsJson] = '['  + [DetailsJson] + ']'

..for op's answer/table..

UPDATE Offers
SET [DetailsJson] = concat(N'["', string_escape([Details], 'json'), N'"]');



declare @col nvarchar(100) = N'
a b c " : [ ] ]
x
y
z'


select  concat(N'["', string_escape(@col, 'json'), N'"]'), isjson(concat(N'["', string_escape(@col, 'json'), N'"]'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM