大数据

SQLite json操作

json_type

在 SQLite 中,要判断一个 JSON 值(value)的类型是 字符串(string)、数字(integer 或 real)、布尔值、null 还是 对象/数组,应使用内置函数:

✅ 推荐方法:json_type(json, path)

该函数返回 JSON 值在指定路径下的类型名称字符串,返回值包括:

返回值含义
'null'JSON 的 null
'integer'整数(如42
'real'浮点数(如3.14
'text'字符串(如"hello")⚠️注意:不是'string',而是'text'
'true'布尔 true
'false'布尔 false
'object'JSON 对象{}
'array'JSON 数组[]

示例:判断类型

假设表如下

CREATE TABLE test (data TEXT);
INSERT INTO test VALUES
  ('{"value": "123"}'),        -- 字符串
  ('{"value": 123}'),          -- 整数
  ('{"value": 123.45}'),       -- 浮点数
  ('{"value": true}'),         -- 布尔
  ('{"value": null}'),         -- null
  ('{"value": "hello"}');      -- 字符串

查询每个值的类型:

SELECT 
  data,
  json_type(data, '$.value') AS value_type
FROM test;

结果:

datavalue_type
{"value": "123"}text
{"value": 123}integer
{"value": 123.45}real
{"value": true}true
{"value": null}null
{"value": "hello"}text

✅ 如何区分“字符串” vs “数字”?

你可以这样写条件判断:

SELECT 
  json_extract(data, '$.value') AS raw_value,
  CASE json_type(data, '$.value')
    WHEN 'text'    THEN 'string'
    WHEN 'integer' THEN 'number (int)'
    WHEN 'real'    THEN 'number (float)'
    ELSE json_type(data, '$.value')
  END AS classified_type
FROM test;

或者仅检查是否为字符串:

SELECT * FROM test
WHERE json_type(data, '$.value') = 'text';

仅检查是否为数字(整数或浮点):

SELECT * FROM test
WHERE json_type(data, '$.value') IN ('integer', 'real');

✅ 总结
要判断 SQLite 中 JSON 值的类型,json_type(json, path)
字符串 → 'text'
整数 → 'integer'
浮点数 → 'real'