Digging Down into JSON data with the MySQL Functions -- A Question from Peter Zaitsev

How do you dig down into the JSON data, say like in comments on a blog post? This is a badly paraphrased question from Peter Zaitsev of Percona at the end of a recent presentation of mine at the Great Wide Open conference. I have to admit I had not done like that with JSON data but it had to be able to be done, right? Surely it can be done. Can't it? Time to dig. I could not find an example of JSON data on a blog with comments. But the good folks at Mongo had an example of a restaurant with grades.

{
"address": {
"building": "1007",
"coord": [ -73.856077, 40.848447 ],
"street": "Morris Park Ave",
"zipcode": "10462"
},
"borough": "Bronx",
"cuisine": "Bakery",
"grades": [
{ "date": { "$date": 1393804800000 }, "grade": "A", "score": 2 },
{ "date": { "$date": 1378857600000 }, "grade": "A", "score": 6 },
{ "date": { "$date": 1358985600000 }, "grade": "A", "score": 10 },
{ "date": { "$date": 1322006400000 }, "grade": "A", "score": 9 },
{ "date": { "$date": 1299715200000 }, "grade": "B", "score": 14 }
],
"name": "Morris Park Bake Shop",
"restaurant_id": "30075445"
}
So how do we get the grade information and just the grades (A,A,A,A, and B) from grades?

I created a quick little table named restaurant with a single column named data for this test and then added the above document to the table. Yeah, real creative on the table and columns names there. Let's look at the fields, or keys.

mysql> select json_keys(data) from restaurant;
+----------------------------------------------------------------------+
| json_keys(data) |
+----------------------------------------------------------------------+
| ["name", "grades", "address", "borough", "cuisine", "restaurant_id"] |
+----------------------------------------------------------------------+
1 row in set (0.01 sec)

mysql>
So can we see the path to the grades key? Yes, but not the date, grade, or score keys from under the grades tag. Note that in the case the 'one' or 'all' second argument returns the same result.
mysql> select json_contains_path(data,'one','$.grades') from restaurant;
+-------------------------------------------+
| json_contains_path(data,'one','$.grades') |
+-------------------------------------------+
| 1 |
+-------------------------------------------+
1 row in set (0.00 sec)
Grab the grades.

mysql> select json_extract(data,'$.grades') from restaurant\G
*************************** 1. row ***************************
json_extract(data,'$.grades'): [{"date": {"$date": 1393804800000}, "grade": "A",
"score": 2}, {"date": {"$date": 1378857600000}, "grade": "A", "score": 6}, {"da
te": {"$date": 1358985600000}, "grade": "A", "score": 10}, {"date": {"$date": 13
22006400000}, "grade": "A", "score": 9}, {"date": {"$date": 1299715200000}, "gra
de": "B", "score": 14}]
1 row in set (0.00 sec)

This is all the info from the grades tag. Now to whittle this down to just the individual grade entries. We can get the individual grades as $.grades.[N] such as:

mysql> select json_extract(data, '$.grades[1]') from restaurant\G
*************************** 1. row ***************************
json_extract(data, '$.grades[1]'): {"date": {"$date": 1378857600000}, "grade": "
A", "score": 6}
1 row in set (0.00 sec)

mysql> select json_extract(data, '$.grades[4]') from restaurant\G
*************************** 1. row ***************************
json_extract(data, '$.grades[4]'): {"date": {"$date": 1299715200000}, "grade": "
B", "score": 14}
1 row in set (0.00 sec)

Much closer!

And then the individual grade from the 4th entry:


mysql> select json_extract(json_extract(data, '$.grades[4][0]'),'$.grade') from
restaurant;
+--------------------------------------------------------------+
| json_extract(json_extract(data, '$.grades[4][0]'),'$.grade') |
+--------------------------------------------------------------+
| "B" |
+--------------------------------------------------------------+
1 row in set (0.00 sec)
I need to go read up on JSON pathing and experiment so I can grab all the grades at once but right now I fell like I am halfway done with the 'homework' Peter assigned.

Nhận xét

Bài đăng phổ biến từ blog này

Using MySQL to Output JSON

Generated MySQL Columns and Changing Values

MySQL Document Store: Getting Started

php


Save 50% on frames when you sign up for the GlassesShop.com newsletter!
Free Shipping At GlassesShop on orders $49+ ! No code required -
Weekly Deals starting at $6.95 plus an extra 20% off on orders $39+ At GlassesShop.com!
BUY ONE GET ONE FREE– use coupon code GSBOGO At GlassesShop.com - Ends 12/31/18
First Pair Free! Use Coupon Code FIRSTFREE At GlassesShop.com – Expires 12/31/2018
New Year, New Savings! Buy one Get one FREE! Use Code GSBOGO Details At GlassesShop.com
Best Buy Co, Inc.
Best Buy Co, Inc.
Best Buy Co, Inc.
button
banner
American National Standards Institute Inc.
SM_125x125button
SM_468x60banner
Iolo technologies, LLC
US/EU Warehouse Super Deal + Extra 10% OFF Code(GOFUN)
Up to 40% OFF + Extra 10% OFF Indoor & Patio Furniture(Code: fubuying)
Thousands of Car Accessories@TOMTOP.com
Thousands of Car Accessories@TOMTOP.com





























Seleção especial para os fãs de Harry Potter! Livros e artigos diversos inspirados na história de Harry, Hermione, Rony e cia!
Cupom exclusivo para os livros da série Harry Potter - CUPOM = POMODEOURO
Dia das crianças Submarino, até 10% off em brinquedos - CUPOM = VEMPROPLAY
10% off em telefonia - CUPOM = ALO10
Home
submarino.com.br
submarino.com.br
Planeta Criança - Diversos produtos com desconto para o Dia das Crianças
Zizo
banner
button
Lançamento FIFA 18 Edição Standard Microsoft Store Brazil
Lançamento FIFA 18 Edição Standard Microsoft Store Brazil




Contentmart
Hire - 468 x 60banner
Article in $3 - 125x125button
Os produtos mais vendidos na Multiar!
Home

Multiar
Home





Mochilas para Notebook Samsonite com Frete Grátis Sul e Sudeste
Conversor e gravador digital com Frete Grátis Brasil (exceto Norte)
Mouses HP com Frete Grátis Sul e Sudeste
WalmartBR
WalmartBR
WalmartBR
WalmartBR
HOMEPAGE
NOTEBOOKS
ALL IN ONE
IMPRESSORAS E SCANNERS
CARTUCHOS E TONERS
ACESSÓRIOS



Nossa melhor proteção para PC, Mac ou dispositivos móveis De R$ 109,00 por R$ 69,00
Nossa melhor proteção para todas as suas formas de se conectar De R$ 169,00 por R$ 99,00
Nossa melhor proteção, mais backup de PC e recursos de segurança da família para você e as pessoas importantes na sua vida De R$ 249,00 por R$ 139,00
Symantec Brazil
Symantec Brazil
Os produtos mais vendidos no ShopFácil!
HOME ShopFacil


eGlobal Central
GenericPro_1.jpgbanner
Relógios -5% de desconto no - CUPOM = FDA5-FBA4-582B-19D3




Informática