从MEMSQL读取JSON

时间:2016-08-11 17:36:19

标签: json memsql

遇到JSON / MEMSQL问题。这是我的表:

CREATE TABLE `MEMSQLPOLYGLOT`  ( 
    ID BIGINT AUTO_INCREMENT,
    `DATA`  JSON NULL,
    PRIMARY KEY (ID)
);

这是我试图阅读的记录:

 insert into MEMTEST (DATA) values 
('
{
    "EnterpriseMessage" : 
        {
            "Body" :
            [
                {
                    "AccountNumber":"ABCD",
                    "AdminCompany":null,
                    "BrokerNumber":"WWonka"
                },
                {
                    "AccountNumber":"CSNE",
                    "AdminCompany":null,
                    "BrokerNumber":"ZWiza"
                }
            ],
        "Header" :
            {
                "mimetye":"application/vnd.ms-powerpoint",
                "destinationsystem":"ETL",
                "requiresack":"FALSE",
                "SimpArr": 
                    [
                        "BYTS6181",
                        "EVU98124",
                        "Genesys"
                    ],
                "EmptyFile":1
            }
    }

}
');

我可以在标题中读取SimpArr数组。

SELECT DATA::EnterpriseMessage::Header::SimpArr from MEMTEST;

返回:

["BYTS6181","EVU98124","Genesys"]

我还可以传入一个键索引来获取特定值,例如:

select JSON_EXTRACT_JSON(DATA::EnterpriseMessage::Body, 1) from MEMTEST;

这将返回SimpArr的第二个值,因为它是一个从零开始的索引。

我还可以读取Body中的对象数组:

select JSON_EXTRACT_JSON(DATA::EnterpriseMessage::Body, 0) from MEMTEST;

返回该数组中的第一个对象:

{
    "AccountNumber":"ABCD",
    "AdminCompany":null,
    "BrokerNumber":"WWonka"
}

但是,我无法找到读取此对象的各个属性的方法。

有人有什么想法吗?

1 个答案:

答案 0 :(得分:2)

您可以将密钥作为额外参数传递给JSON_EXTRACT_JSON

mysql> select JSON_EXTRACT_JSON(DATA::EnterpriseMessage::Body, 0, "AccountNumber") from MEMTEST;
+----------------------------------------------------------------------+
| JSON_EXTRACT_JSON(DATA::EnterpriseMessage::Body, 0, "AccountNumber") |
+----------------------------------------------------------------------+
| "ABCD"                                                               |
+----------------------------------------------------------------------+
1 row in set (0.08 sec)

JSON_EXTRACT_JSON接受任意数量的参数,字符串键或整数数组索引。例如,我们可以在上面的示例中展开::语法:

select JSON_EXTRACT_JSON(DATA, "EnterpriseMessage", "Body", 0, "AccountNumber") from MEMTEST;

另请注意,返回值中包含双引号。那是因为你提取了JSON,而字符串的JSON表示有双引号。如果您确实想要获取字符串,请使用JSON_EXTRACT_STRING

mysql> select JSON_EXTRACT_STRING(DATA, "EnterpriseMessage", "Body", 0, "AccountNumber") from MEMTEST;
+----------------------------------------------------------------------------+
| JSON_EXTRACT_STRING(DATA, "EnterpriseMessage", "Body", 0, "AccountNumber") |
+----------------------------------------------------------------------------+
| ABCD                                                                       |
+----------------------------------------------------------------------------+
1 row in set (0.07 sec)