8

With json as

{ "First Name": {"nickname" : "Abc"} }

in json column 'name' of mysql database.

How do I extract such rows in mysql.

Select * from users where name."$.First Name.nickname" = "abc";

won't work. Any solution because I cannot change the json structure in database.

2
  • use like query <?php $srch = '%"nickname" : "Abc"%'; $ss= 'Select * from users where column_name like '.$srch; echo $ss; ?>
    – JYoThI
    Commented Jun 14, 2016 at 10:13
  • This doc might help
    – Thamilhan
    Commented Jun 14, 2016 at 10:15

2 Answers 2

23

Found the answer:

Select * from users where name."$.""First Name"".nickname" = "abc";

you need to double quote the key of JSON with a space.

3
  • name->"$."... * Commented Oct 19, 2017 at 13:37
  • Hello, We are on mysql version 5.5 and i have one column called USER_JSON in which datas are stored like this [{"userId":"LQ2138C","seenFlag":"0","seenDate":"0000\/00\/00 00:00:00"},{"userId":"LQ1839C","seenFlag":"0","seenDate":"0000\/00\/00 00:00:00"},{"userId":"LQ4396C","seenFlag":"0","seenDate":"0000\/00\/00 00:00:00"},{"userId":"LQ1462C","seenFlag":"0","seenDate":"0000\/00\/00 00:00:00"},{"userId":"LQ58522C","seenFlag":"0","seenDate":"0000\/00\/00 00:00:00"},{"userId":"LQ1687C","seenFlag":"0","seenDate":"0000\/00\/00 00:00:00"}] Commented Feb 15, 2018 at 12:20
  • 2
    You can also do: select * from users where name->'$."First Name".nickname' = "abc", which, I think, is clearer.
    – RayCh
    Commented Oct 15, 2019 at 15:41
-1

First you need to convert json into array using json_decode

$str='{ "First Name": {"nickname" : "Abc"} }';
$data=json_decode($str,TRUE);

The output of json_decode is

Array
(
    [First Name] => Array
        (
            [nickname] => Abc
        )

)

Extract nickname form array

 echo $name=$data['First Name']['nickname'];

And use in query as

Select * from users where name = '$name';
2
  • 1
    OP says I cannot change the json structure in database.
    – Thamilhan
    Commented Jun 14, 2016 at 10:15
  • can't change the json structure in database But it can fetch json form database and extract its value that's the easy way!!
    – Saty
    Commented Jun 14, 2016 at 10:18

Not the answer you're looking for? Browse other questions tagged or ask your own question.