mysql - 搜索 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.Identity
为com.parallelorigin.code.ecs.components.Identity
,向同一个 json 对象添加一个新的“名称”字段,调整现有标签并完全删除 typeID。
在 MySQL 中修改 Json 数组的最优雅/最简单的方法是什么?
解决方案
给定一个值,您可以获取 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 效果。
优雅的解决方案是以标准化方式存储数据。
推荐阅读
- cluster-computing - SLURM 如何为每个节点启动一次脚本
- reactjs - 关于 React 生命周期函数的问题
- arrays - FindIndex 值连续返回为 -1?
- oracle - 如何检查模式在 oracle 中使用的表空间?
- javascript - Flexbox - 如何将 div 移动到空白空间?
- javascript - 我需要帮助才能恢复默认状态
- javascript - 本地文件路径的 Azure 函数 Node.js REST API 问题
- android - 除非使用 ACTION_OPEN_DOCUMENT_TREE 再次征求用户同意,否则无法使用使用 ACTION_CREATE_DOCUMENT 在共享存储中创建的目录
- jenkins - Jenkins 管道中的 curl 错误 - 找不到 URL
- javascript - 如何将 csv 数据导入 javascript 以创建搜索器?