2023年6月4日日曜日

SQLite3 JSON要素の型を調べる(json_type())

概要

json_type関数を使うと要素の型を調べることが出来る。
判定出来る型は以下の通り。

型名 意味
object 連想配列

{
    "string_01"   : [ 0, 1, 2, 3]
    , "string_02" : null
}
                                
array 配列

[ 0, 1, 2, 3 ]
                                
integer 整数

10
                                
real 浮動小数点

3.14
                                
true

true
                                
false

false
                                
null NULL値

null
                                
text 文字列

"This is Text."
                                

判定できなかった場合はエラーになる

構文


json_type(json_string, json_path)
                

実行例

環境
  • Windows 10 64bit
  • SQLite3 (3.41.2) Command-Line Shell

sqlite> -- # 1.
sqlite> select json_type('
'  ...>     {
'  ...>         "string_01"   : [ 0, 1, 2, 3]
'  ...>         , "string_02" : null
'  ...>     }
'  ...> ');
object

sqlite> -- # 2.
sqlite> select json_type('
'  ...>     [ 0, 1, 2, 3 ]
'  ...> ');
array

sqlite> -- # 3.
sqlite> select json_type('10');
integer

sqlite> -- # 4.
sqlite> select json_type('3.14');
real

sqlite> -- # 5.
sqlite> select json_type('true');
true

sqlite> -- # 6.
sqlite> select json_type('false');
false

sqlite> -- # 7.
sqlite> select json_type('null');
null

sqlite> -- # 8.
sqlite> select json_type('"This is Text"');
text

                    
  1. いわゆる連想配列は「object」として判定される
  2. 通常の配列の場合は「array」
  3. 整数は「integer」
  4. 浮動小数点は「real」
  5. 真偽値のtrueは「true」
  6. 真偽値のfalseは「false」
  7. nullは「null」
  8. 文字列は「text」

なお、json_type()の返り値自体は文字列型となっている。

JSON型以外を引数に指定すると以下のような結果になる


sqlite> .nullvalue [null]
sqlite> -- # 1.
sqlite> select json_type('This is Text');
Runtime error: malformed JSON

sqlite> -- # 2.
sqlite> select json_type(10);
integer

sqlite> -- # 3.
sqlite> select json_type(3.14);
real

sqlite> -- # 4.
sqlite> select json_type(true);
integer

sqlite> select json_type(false);
integer

sqlite> -- # 5.
sqlite> select json_type(null);
[null]
                    
  1. JSON形式になっていない場合はエラーとなる
  2. 文字列ではなく素の整数でもintegerとして判定される
  3. 文字列ではなく素の小数点でもrealとして判定される
  4. trueやbooleanは数値型として判定される
  5. nullはnullが返り値となる

参考URL