How to create a JSON object in MySql with a boolean value?
Asked Answered
F

4

6

I would like my MySql query to return a JSON object that looks as follows:

{"name": "Piotr", "likesMysql": true}

This seems to be working fine when I do:

SELECT json_object(
    'name', 'Piotr',
    'likesMysql', TRUE
)

However when I try to derive the likesMysql from an if expression I get 0 and 1 instead of false and true e.g.:

SELECT json_object(
    'name', 'Piotr',
    'likesMysql', if(4 MOD 2 = 0, TRUE, FALSE)
)

results in

{"name": "Piotr", "likesMysql": 1}

How do I use the json_object to construct a JSON object that has true or false as property value?

Fibro answered 6/3, 2018 at 13:19 Comment(0)
F
22

This seems to be a bug in MySql.

You can workaround it though with cast(true as json) e.g.:

SELECT json_object(
    'name', 'Piotr',
    'likesMysql', if(4 MOD 2 = 0, cast(TRUE as json), cast(FALSE as json))
)
Fibro answered 6/3, 2018 at 13:30 Comment(2)
Having just come across this post, I respectfully have to comment that this is probably the most correct answer, both programmatically and for readability purposes. Although the answer provided by Aniket may work under most conditions. IMHO.Elexa
Works with 5.7.34Astrea
F
5

Simply go with following,

SELECT json_object( 'name', 'Piotr', 'likesMysql', if(5 MOD 2 = 0, TRUE, FALSE) is true )

Hope you get desired result with this :)

Flushing answered 6/3, 2018 at 13:29 Comment(0)
T
2

Aniket Bhansali's approach could be simplified as:

select json_object(
    'bool_true', (4 mod 2 = 0) is true,
    'bool_false', 0 is true) b;

which returns

{"bool_true": true, "bool_false": false}

Tested on mysql 8.

Thuja answered 17/3, 2020 at 1:17 Comment(0)
D
1
SELECT json_object(
   'name', 'Piotr',
   'likesMysql', 4 MOD 2 != 0
)
Dearth answered 19/5, 2020 at 12:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.