Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to query a JSON element

Let's say I have a Postgres database (9.3) and there is a table called Resources. In the Resources table I have the fields id which is an int and data which is a JSON type.

Let's say I have the following records in said table.

  • 1, {'firstname':'Dave', 'lastname':'Gallant'}
  • 2, {'firstname':'John', 'lastname':'Doe'}

What I want to do is write a query that would return all the records in which the data column has a json element with the lastname equal to "Doe"

I tried to write something like this:

records = db_session.query(Resource).filter(Resources.data->>'lastname' == "Doe").all() 

Pycharm however is giving me a compile error on the "->>"

Does anyone know how I would write the filter clause to do what I need?

like image 291
Dave Gallant Avatar asked Apr 30 '15 17:04

Dave Gallant


People also ask

Can we query on JSON data?

You can query JSON data using a simple dot notation or, for more functionality, using SQL/JSON functions and conditions. You can create and query a data guide that summarizes the structure and type information of a set of JSON documents.

How can I get specific data from JSON?

Getting a specific property from a JSON response object Instead, you select the exact property you want and pull that out through dot notation. The dot ( . ) after response (the name of the JSON payload, as defined arbitrarily in the jQuery AJAX function) is how you access the values you want from the JSON object.

How do I query a JSON column in MySQL?

How to Retrieve data from JSON column in MySQL. MySQL provides two operators ( -> and ->> ) to extract data from JSON columns. ->> will get the string value while -> will fetch value without quotes. As you can see ->> returns output as quoted strings, while -> returns values as they are.


2 Answers

Try using astext

records = db_session.query(Resource).filter(               Resources.data["lastname"].astext == "Doe"           ).all() 

Please note that the column MUST have a type of a JSONB. The regular JSON column will not work.

like image 168
Anzel Avatar answered Oct 02 '22 14:10

Anzel


Also you could explicitly cast string to JSON (see Postgres JSON type doc).

from sqlalchemy.dialects.postgres import JSON from sqlalchemy.sql.expression import cast db_session.query(Resource).filter(     Resources.data["lastname"] == cast("Doe", JSON) ).all() 
like image 32
kc41 Avatar answered Oct 02 '22 14:10

kc41