【问题标题】:How do I update a json object value by referencing itself in a sqlite table?如何通过在 sqlite 表中引用自身来更新 json 对象值?
【发布时间】:2021-08-07 19:04:40
【问题描述】:

假设我有一个表 features,其中有一列 data 包含 json 对象。

CREATE TABLE features ( id INTEGER PRIMARY KEY, data json )

现在,一个示例数据对象可能是:

{"A":
   {"B":
      {"coordinates":[
         {"x":1, "y":1},
         {"x":10, "y":10}
       ]
    }
}

现在我需要遍历data 列中的所有数据,并将coordinates 的值加倍。

我尝试将其设置为自己的值除以 0.5,但这似乎适用于第一行,然后将所有其他行设置为完全相同的值。

update features
set data = 
(select json_set(features.data, "$.A.B.coordinates[0].x", (select json_extract(features.data, "$.A.B.coordinates[0].x")/0.5 from features))
from features);

如何在json_set 中引用它自己的值并为每一行重复?遍历每一行并将坐标加倍的最佳方法是什么?

【问题讨论】:

    标签: json sqlite


    【解决方案1】:

    不需要SELECT 声明。
    可以直接参考同一行data列的值:

    UPDATE features
    SET data = json_set(
                 features.data, 
                 "$.A.B.coordinates[0].x", json_extract(features.data, "$.A.B.coordinates[0].x") * 2
               );
    

    或者,如果您想更新所有xs 和ys:

    UPDATE features
    SET data = json_set(
                 features.data, 
                 "$.A.B.coordinates[0].x", json_extract(features.data, "$.A.B.coordinates[0].x") * 2,
                 "$.A.B.coordinates[0].y", json_extract(features.data, "$.A.B.coordinates[0].y") * 2,
                 "$.A.B.coordinates[1].x", json_extract(features.data, "$.A.B.coordinates[1].x") * 2,
                 "$.A.B.coordinates[1].y", json_extract(features.data, "$.A.B.coordinates[1].y") * 2
           );
    

    请参阅demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-25
      • 2016-01-07
      • 2019-01-30
      • 2013-03-11
      • 1970-01-01
      • 2017-11-16
      相关资源
      最近更新 更多