【发布时间】:2021-04-02 09:32:43
【问题描述】:
我将以下 json 结构存储到 mysql 中
{
"somefield": "0",
"date": "2020-12-01",
"caption": null,
"field": [
{
"id_type1": "5192"
},
{
"id_type2": "3285"
},
{
"id_type2": "3638"
},
{
"id_type2": "3750"
},
{
"id_type2": "3760"
},
{
"id_type1": "3161"
},
{
"id_type1": "1044"
}
],
"question": "",
"people": [],
"title": ""
}
当我提交一个表单时,我想按名称检索非空值,然后更新 json 字段
假设我提交了 2 个字段,date 和 field
字段
[{"id_type1":5192},{"id_type2":3285},{"id_type2":3638},{"id_type2":3750},{"id_type2":3760},{"id_type1":3161},{"id_type1":1044},{"id_type1":8081}]
日期
'2021-04-02'
我想用这些值更新 json 字段
UPDATE table
SET
json_champ = JSON_SET(json_champ, '$."field"', '[{"id_type1":5192},{"id_type2":3285},{"id_type2":3638},{"id_type2":3750},{"id_type2":3760},{"id_type1":3161},{"id_type1":1044},{"id_type1":8081}]', '$."date"', '2020-12-01')
WHERE id = '52907';
日期一切正常,但字段被转义
"field": "[{\"id_type1\":5192},{\"id_type2\":3285},{\"id_type2\":3638},{\"id_type2\":3750},{\"id_type2\":3760},{\"id_type1\":3161},{\"id_type1\":1044},{\"id_type1\":8081}]"
预期
"field": [{"id_type1":5192},{"id_type2":3285},{"id_type2":3638},{"id_type2":3750},{"id_type2":3760},{"id_type1":3161},{"id_type1":1044},{"id_type1":8081}]
如果我将预期的输出直接粘贴到 PMA 中,它会按预期工作
粘贴
{
"somefield": "0",
"date": "2020-12-01",
"caption": null,
"field": [{"id_type1":5192},{"id_type2":3285},{"id_type2":3638},{"id_type2":3750},{"id_type2":3760},{"id_type1":3161},{"id_type1":1044},{"id_type1":8081}],
"question": "",
"people": [],
"title": ""
}
生成的 sql 查询
<?php
$sqlUpdate = " UPDATE table
SET
json_champ = JSON_SET(json_champ, '$."field"', '".json_encode($fieldValues, , JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT)."', '$."date"', '2020-12-01')
WHERE id = '".$id."'";
【问题讨论】:
-
我有以下 json 字符串 你的数据字符串是 JSON 数组。您不能使用 JSON_SET() 指定特定于 JSON 对象的路径。
-
那我该怎么办?