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

后端 未结 4 1436
星月不相逢
星月不相逢 2021-01-16 06:09

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

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

This seems to be wor

相关标签:
4条回答
  • 2021-01-16 06:38

    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))
    )
    
    0 讨论(0)
  • 2021-01-16 06:40

    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.

    0 讨论(0)
  • 2021-01-16 07:00
    SELECT json_object(
       'name', 'Piotr',
       'likesMysql', 4 MOD 2 != 0
    )
    
    0 讨论(0)
  • 2021-01-16 07:03

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

    0 讨论(0)
提交回复
热议问题