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

…衆ロ難τιáo~ 提交于 2019-12-02 17:00:39

问题


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?


回答1:


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))
)



回答2:


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 :)



来源:https://stackoverflow.com/questions/49131832/how-to-create-a-json-object-in-mysql-with-a-boolean-value

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