从查询结果的json对象中删除值为“ NULL”的K,V对

时间:2018-11-08 14:05:45

标签: sqlite sqlite-json1

以下内容为我提供了一个结果:{"a":null,"b":99.0,"c":null} 我希望得到{"b":99.0}的结果,以便可以在JSON补丁中使用该结果。如何使用sqlite / json1实现此目标?

DROP TABLE IF EXISTS test;
CREATE TABLE test (
    id INTEGER PRIMARY KEY, 
     a REAL, b REAL, c REAL
);

INSERT INTO test(a,b,c) 
VALUES (1,2,3), (1,99,3);

SELECT json_object(
           'a', NULLIF(new.a, curr.a), 
           'b', NULLIF(new.b, curr.b),
           'c', NULLIF(new.c, curr.c)
       ) AS result
  FROM test curr
 INNER JOIN test new ON curr.id
 WHERE new.id = 2 AND curr.id = new.id -1 ;

1 个答案:

答案 0 :(得分:0)

以后有些摆弄:

SELECT json_group_object(key, value) 
  FROM json_each(json('{"a":null, "b":99.0, "c":null}')) AS result
 WHERE result.value IS NOT NULL;

得出{"b":99.0}

所以整个事情像这样:

DROP TABLE IF EXISTS test;
CREATE TABLE test (
    id INTEGER PRIMARY KEY, 
     a REAL, 
     b REAL, 
     c REAL
);

INSERT INTO test(a,b,c) 
VALUES (1,2,3), (1,99,3), (2,99,4), (1,999,3);

WITH J(kv) AS (
  SELECT json_object(
           'a', NULLIF(new.a, curr.a), 
           'b', NULLIF(new.b, curr.b),
           'c', NULLIF(new.c, curr.c)
         )
    FROM test curr
   INNER JOIN test new ON curr.id
   WHERE new.id = 2 AND curr.id = new.id -1
)
SELECT json_group_object(key, value) AS result 
  FROM json_each((SELECT kv FROM J)) AS kv
 WHERE kv.value IS NOT NULL;