首页 > 解决方案 > 搜索 json 值并在 mysql 中替换它的最优雅的方法?

问题描述

我有一个名为的表Entity,它存储了一堆 json。

Entity
ID | Json 

Json 基本上是一个 json 对象数组。json对象的顺序每次都不一样...

[
    {
        "class" : "com.parallelorigin.code.ecs.components.Identity",
        "id" : 0,
        "tag" : "player",
        "typeID" : "3:1"
    },
    {
        "class" : "com.parallelorigin.code.ecs.components.transform.Transform",
        "position" : {
            "x" : 51.845858,
            "y" : 8.299743
        },
        "previousPos" : null
    },
    {
        "class" : "com.parallelorigin.code.ecs.components.collision.RangeCollider",
        "range" : 0.000100
    },
    {
        "class" : "com.parallelorigin.code.ecs.components.transform.Movement",
        "moveTo" : null,
        "speed" : 0.001000
    },
    {
        "baseDamage" : 2,
        "class" : "com.parallelorigin.code.ecs.components.combat.PhysicalDamage",
        "damage" : 0
    },
    {
        "class" : "com.parallelorigin.code.ecs.components.graphical.Mesh",
        "id" : 6
    },
    {
        "class" : "com.parallelorigin.code.ecs.components.items.Inventory"
    },
    {
        "class" : "com.parallelorigin.code.ecs.components.combat.Health",
        "health" : 100,
        "maxHealth" : 100
    },
    {
        "attackSpeed" : 1,
        "baseAttackSpeed" : 1,
        "class" : "com.parallelorigin.code.ecs.components.combat.AttackSpeed"
    },
    {
        "class" : "com.parallelorigin.code.ecs.components.animation.AnimationController",
        "controllerName" : "standardAnimationController"
    }
]

我想替换一些类路径,向 json 对象添加新字段,修改现有字段或删除它们。

例如,我想替换com.parallelorigin.code.ecs.components.Identitycom.parallelorigin.code.ecs.components.Identity,向同一个 json 对象添加一个新的“名称”字段,调整现有标签并完全删除 typeID。

在 MySQL 中修改 Json 数组的最优雅/最简单的方法是什么?

标签: mysqlsqljson

解决方案


给定一个值,您可以获取 json 数组的元素:

mysql> select substring_index(json_unquote(json_search(json, 'one', 'com.parallelorigin.code.ecs.components.Identity')), '.', 1) as element from entity;
+---------+
| element |
+---------+
| $[0]    |
+---------+

这给出了您需要替换的元素的位置。然后你可以使用 JSON_REPLACE() 来改变它,像这样:

UPDATE Entity SET json = 
  json_replace(json, 
    substring_index(json_unquote(json_search(json, 'one', 'com.parallelorigin.code.ecs.components.Identity')), '.', 1),
    json_object(
      'class', 'com.parallelorigin.code.ecs.components.Identity', 
      'id', 0, 
      'name', 'some name')
  )
WHERE id = 1;

就是方法,但它没有什么优雅的地方。这是在 MySQL 中使用 JSON 的典型方式。在 SQL 数据库中使用 JSON 通常会使数据操作更加困难。

在 MySQL 中使用 JSON,您几乎肯定会体验到Inner-Platform 效果

优雅的解决方案是以标准化方式存储数据。


推荐阅读