在 mysql 中键入关键字在 json 中查找

Find in json by key in mysql

我有一个 json,我想提取一个键的值。我知道密钥名称但不知道位置。我的 json 很复杂,在 mysql 中看起来像这样:

set @jsonstr:='
{
    "glossary": {
        "title": "example glossary",
        "GlossDiv": {
            "title": "S",
            "GlossList": {
                "GlossEntry": {
                    "ID": "SGML",
                    "SortAs": "SGML",
                    "GlossTerm": "Standard Generalized Markup Language",
                    "Acronym": "SGML",
                    "Abbrev": "ISO 8879:1986",
                    "GlossDef": {
                        "para": "A meta-markup language, used to create markup languages such as DocBook.",
                        "GlossSeeAlso": ["GML", "XML"]
                    },
                    "GlossSee": "markup"
                }
            }
        }
    }
}
';

例如,我想搜索关键字 "Acronym"。我想要完整路径/或直接它的值 ["SGML"] 以便我可以进一步处理它。

我在执行以下操作,结果返回 null

select JSON_Search(@jsonstr,'all', '%Acronym%')

我的要求:


编辑

有效,所以我现在尝试使用更新后的 json,看起来像

    set @jsonstr:='
{
    "glossary": {
        "title": "example glossary",
        "GlossDiv": {
            "title": "S",
            "GlossList": {
                "GlossEntry": {
                    "ID": "SGML",
                    "SortAs": "SGML",
                    "GlossTerm": "Standard Generalized Markup Language",
                    "Acronym": "SGML",
                    "Abbrev": "ISO 8879:1986",
                    "GlossDef": {
                        "para": "A meta-markup language, used to create markup languages such as DocBook.",
                        "GlossSeeAlso": ["GML", "XML"],
                        "Acronym" : "another value"
                    },
                    "GlossSee": "markup"
                }
            }
        }
    }
}
';

所以现在查询

select JSON_EXTRACT(@jsonstr,'$**.Acronym')

返回

["SGML", "another value"]

但是像这样我将无法获取具有我的目标密钥的各个位置的路径。

问题: 如果我能得到一个 table 返回,其中 "key location" 作为第一列,它们各自的值在第二列。

我想你想要这个查询:

SELECT JSON_EXTRACT(@jsonstr,'$**.Acronym')

JSON_Search 在 JSON 对象中查找值。您知道要查找的密钥的名称,因此您只需使用路径,在 https://dev.mysql.com/doc/refman/5.7/en/json-path-syntax.html with examples at https://dev.mysql.com/doc/refman/5.7/en/json-search-functions.html#function_json-search

中进行了说明

可能会迟到,但试试这个:

SET @junkJs:=JSON_OBJECT('a', JSON_OBJECT('b', 'xxxx'));

SET @x:=JSON_SEARCH(replace(@junkJs, '"b":', '"j":"junk", "b":'), 'all', 'junk');

select replace(@x, '.j', '');