【问题标题】:mysql update json field getting quotedmysql更新json字段被引用
【发布时间】: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 个字段,datefield 字段

[{"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 对象的路径。
  • 那我该怎么办?

标签: php mysql json


【解决方案1】:

据我所知,唯一的区别是在json的开头添加字段,然后将字符串插入表中?

$json_string = '[{"id_type1":5192},{"id_type2":3285},{"id_type2":3638},{"id_type2":3750},{"id_type2":3760},{"id_type1":3161},{"id_type1":1044}]';
   
$ammended_string = json_encode(['field' => json_decode($json_string)]);

$sqlUpdate = " UPDATE table 
SET 
json_champ = '".$ammended_string ."'
WHERE id = '".$id."'";

如果我错了,请纠正我,但认为你可能有点过于复杂了。

【讨论】:

  • 事实上,我的 json 数据查询中有多个字段,如果提交的值存在于 json 中,则在 post 中构建提交的值,然后将其获取并更新 mysql 中的 json
  • 那不是你的问题。
猜你喜欢
  • 2017-06-11
  • 2017-05-05
  • 1970-01-01
  • 1970-01-01
  • 2023-01-19
  • 2021-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多