0

我尝试了很多将嵌套对象添加到我的 mysql 列,但它只是将其添加为新键。这是我的样本:

{
    "Vocab": {
        "username":"132423424",

        "Mother": {
           "code":"1",
      "progress":"1",
      "nextdate":"22-10-2020",
 "lastcheck":"22-10-2020"
        },
        "Father": {
           "code":"2",
      "progress":"2",
      "nextdate":"22-10-2020",
       "lastcheck":"22-10-2020"
        } 
    }
}

我想在 Vocab 对象下添加这个对象及其内部键:

   "Brother": {
           "code":"3",
      "progress":"1",
      "nextdate":"22-12-2020",
       "lastcheck":"22-12-2020"
        } 

任何帮助,将不胜感激

4

2 回答 2

0

一种选择是使用JSON_INSERT()函数:

SET @data = '{
    "Vocab": {
        "username":"132423424",
        "Mother": {
        "code":"1",
        "progress":"1",
        "nextdate":"22-10-2020",
        "lastcheck":"22-10-2020"
        },
        "Father": {
        "code":"2",
        "progress":"2",
        "nextdate":"22-10-2020",
        "lastcheck":"22-10-2020"
        } 
    }
}';

SET @data2 = '{ "code": "3", "progress":"1", "nextdate":"22-12-2020", "lastcheck":"22-12-2020" }';


SELECT JSON_PRETTY(
          REPLACE( 
                 REPLACE(
                         REPLACE(
                                 JSON_INSERT(@data, '$.Vocab.Brother', (@data2))
                                ,'\\"','"')
                         ,'"{','{') 
                ,'}"','}') ) AS 'New JSON';

Demo

最后需要使用REPLACE()函数来格式化与双引号相关的格式。

于 2020-07-26T08:35:15.007 回答
0

当您使第二个数据也是有效的 JSON 时

 {   "Brother": {
       "code":"3",
  "progress":"1",
  "nextdate":"22-12-2020",
   "lastcheck":"22-12-2020"
    } }

你使用JSON_MERGE_PATCH

SET @a = '{
    "Vocab": {
        "username":"132423424",

        "Mother": {
           "code":"1",
      "progress":"1",
      "nextdate":"22-10-2020",
 "lastcheck":"22-10-2020"
        },
        "Father": {
           "code":"2",
      "progress":"2",
      "nextdate":"22-10-2020",
       "lastcheck":"22-10-2020"
        } 
    }
}';
SET @b = '{   "Brother": {
           "code":"3",
      "progress":"1",
      "nextdate":"22-12-2020",
       "lastcheck":"22-12-2020"
        } }';
✓

✓
SELECT JSON_MERGE_PATCH(@a, @b);
| JSON_MERGE_PATCH(@a, @b) |
| :------------------------------------------------ -------------------------------------------------- -------------------------------------------------- -------------------------------------------------- -------------------------------------------------- -------------------------------------------------- ---------------------- |
| {“词汇”:{“父亲”:{“代码”:“2”,“下一个日期”:“22-10-2020”,“进度”:“2”,“lastcheck”:“22-10-2020” },“母亲”:{“代码”:“1”,“下一个日期”:“22-10-2020”,“进度”:“1”,“lastcheck”:“22-10-2020”},“用户名": "132423424"}, "兄弟": {"code": "3", "nextdate": "22-12-2020", "progress": "1", "lastcheck": "22-12-2020" "}} |

db<>在这里摆弄

于 2020-07-25T21:25:20.380 回答