Получение значения из строки JSON в чисто MySQL

0

Я ищу один запрос, который просто MySQL. Цель этого запроса - использовать такие вещи, как SUBSTRING_INDEX, CONCAT или что-то еще, что нужно, чтобы найти значение в строке.

Скажем, что строка выглядит примерно так: {"name":34,"otherName":55,"moreNames":12,"target":26,"hello":56,"hi":26,"asd":552,"p":3722,"bestName":11,"cc":6,"dd":10,}

Моя цель - получить значение target, в данном случае 26. Однако "target":26 может не всегда находиться в этом месте в строке. Ни один из других свойств. Кроме того, значение может быть не всегда равным 26. Мне нужно каким-то образом проверить, какое число приходит после "target": но до , после "target": Есть ли способ сделать это?

Теги:

2 ответа

1
Лучший ответ

Вот этот?

create table sandbox (id integer, jsoncolumn varchar(255));
insert into sandbox values (1,'{"name":34,"otherName":55,"moreNames":12,"target":26,"hello":56,"hi":26,"asd":552,"p":3722,"bestName":11,"cc":6,"dd":10}');

mysql root@localhost:sandbox> SELECT jsoncolumn->'$.target' from sandbox;
+--------------------------+
|   jsoncolumn->'$.target' |
|--------------------------|
|                       26 |
+--------------------------+

https://dev.mysql.com/doc/refman/5.7/en/json-search-functions.html

  • 0
    да, это работает! Огромное спасибо! :)
0
Please try this function to get value from JSON string in MYSQL

DROP FUNCTION IF EXISTS CAP_FIRST_CHAR;

DELIMITER $$

CREATE FUNCTION getValueFromJsonSring(jsonStr VARCHAR(250), getKey VARCHAR(250))
  RETURNS VARCHAR(250) deterministic

BEGIN

  DECLARE output VARCHAR(250);  -- Holds the final value.
  DECLARE data VARCHAR(250);    -- Holds the exctracted value from JSON
  SET getKey=CONCAT('"',getKey,'"');
  SET data= TRIM(LEADING ':' FROM 
                substring_index(
                    substring_index(
                        substring_index(
                            substring_index(
                               SUBSTRING(jsonStr, 2, LENGTH(jsonStr)-2)
                                , getKey , '2'), 
                            getKey, 
                            -1
                          )
                        , ',', '1'), 
                    ',', 
                    -1
                )

            );
  SET output =SUBSTRING(data, 2, LENGTH(data)-2);

  RETURN output;
END;
$$
DELIMITER ;

SELECT getValueFromJsonSring('{"amount":"400.34","departmentId":"7","date":"2017-06-02","PONumber":"0000064873","vendor":"44"}',"departmentId");

Ещё вопросы

Сообщество Overcoder
Наверх
Меню