首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >搜索json值并在mysql中替换它的最优雅的方法?

问搜索json值并在mysql中替换它的最优雅的方法?
EN

Stack Overflow用户
提问于 2021-09-01 16:07:27
回答 1查看 93关注 0票数 0

我有一张名为Entity的桌子,里面存储着一堆麻烦事。

代码语言:javascript
复制
Entity
ID | Json 

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

代码语言:javascript
复制
[
    {
        "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.Identity替换com.parallelorigin.code.ecs.components.Identity,向同一个json对象添加一个新的"name“字段,调整现有的标记并完整地删除typeID。

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-09-01 16:19:47

您可以获得给定值的json数组的元素:

代码语言:javascript
复制
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()来更改它,如下所示:

代码语言:javascript
复制
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,您几乎肯定会体验到内平台效应。

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69017259

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档