Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL JSON - How to modify boolean value present in the Json Data

How can I modify the existing boolean value of a json data in SQL Server 2016 - Json?

Below is the script for inserting json Data.

DECLARE @a nvarchar(max) = N'{"employeeName":"Test","isActive":true}';

insert into TestTable(testId,name,jsonData) Values('1','Test',@a) 

I tried to update using below query, but it returns Invalid column name 'false'.

update TestTable
set jsonData = JSON_MODIFY(jsonData,'$.isActive',false)
like image 243
Viresh Mathad Avatar asked Jul 21 '17 04:07

Viresh Mathad


People also ask

How do I change the boolean value in SQL Server?

Sql server does not expose a boolean data type which can be used in queries. Instead, it has a bit data type where the possible values are 0 or 1 . So to answer your question, you should use 1 to indicate a true value, 0 to indicate a false value, or null to indicate an unknown value.

Can you put boolean in JSON?

JSON BooleansValues in JSON can be true/false.

How can change JSON value in SQL Server?

Example 1: Update JSON property value Suppose you wish to update the product value in this JSON, we can use the following code using JSON_MODIFY(). SELECT JSON_MODIFY('{"Brand":"HP","Product":"Laptop"}', '$. Product', 'Laptop') AS 'Updated JSON'; It returns the updated JSON string in the output.

How do you write true or false in JSON?

In Python, "boolean" is analogous to bool . Note that in JSON, true and false are lower case, whereas in Python they are capitalized ( True and False ).


1 Answers

You can accomplish this using CAST(0 as BIT)

update TestTable
set jsonData = JSON_MODIFY(jsonData, '$.isActive', CAST(0 as BIT))

If you want to set it to true, it is simply CAST(1 as BIT) instead.

This works because in SQL, a boolean is represented as a BIT, which can only be 0 or 1. In its translation to JSON, it converts a bit of 0 to false, and a bit of 1 to true.

like image 161
Zork Avatar answered Oct 26 '22 17:10

Zork