Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
SQLAlchemy: How to group by two fields and filter by date
Next article icon

SQLAlchemy filter by json field

Last Updated : 24 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will be discussing the SQLAlchemy filter by JSON field using Python. Before we begin the introduction, to the topic we will be discussing the basics of how to filter by JSON fields using a few examples and a brief introduction to SQLAlchemy, JSON, and JSON fields.

Required Package

pip install SQLAlchemy

What is SQLAlchemy? 

SQLAlchemy is a Python library that provides a nice API for interacting with databases. It has a lot of features, including a powerful ORM (Object-Relational Mapper) that allows you to map Python objects to database tables and vice versa.

Using SQLAlchemy can make it easier to work with databases in your Python code because it provides a consistent interface for interacting with different types of databases by abstracting some of the queries. For more information refer to this article many on SQLAlchamey.

What is JSON?

A JSON file is a file that stores simple data structures and objects in JavaScript Object Notation(JSON) format, which is a standard data interchange format. It is primarily used to transmit data between servers and web applications as an alternative to XML.

What is a JSON field?

A JSON field is a field in a database table that is designed to store JSON data. JSON field is generally used to store complex, multi-level data structures that cannot be easily represented with the traditional database schema. It is beneficial when the data structure is not known in advance or is likely to change over time.

In a database table, a JSON field is usually defined as a column of type JSON or a JSONB. The JSON type stores the JSON data type as plain string, while the JSONB stores it in binary format which is much more efficient to query but is more challenging to read and interpret.

How to query using JSON fields?

To filter a query using a JSON field with SQLAlcoperatoremy, we make use of the filter method and specify a condition that uses the @ operator. The @ checks if the left JSON value is a superset of the right JSON value the other method is shown below in the example. I have used Mysql which is an RDBMS. 

Creating a Database to Filter by JSON field

This code creates a database connection to a MySQL server using the SQLAlchemy library. It then creates a table called employees with two columns, id, and data. The data column is of type JSON, which allows for the storage of JSON data. The code then creates a session, adds a row to the employee table with a JSON object containing first_name, last_name, and age, and commits the changes to the database. Finally, it queries the table for the row where the first_name value is joseph and prints the id of the returned row. The session is closed at the end.

Python
from sqlalchemy import create_engine from sqlalchemy import Column, Integer, String, JSON from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker  # Connects to database engine used mysql engine = create_engine('mysql://roots:PASSWORD@localhost:3306/trial') Base = declarative_base()  # Creating a table in database with two columns id and data # for this example the entire json file is stored in data class MyTable(Base):     __tablename__ = 'employees'     id = Column(Integer, primary_key=True)     data = Column(JSON)   Base.metadata.create_all(engine)  Session = sessionmaker(bind=engine) session = Session()  # Insert a row with a JSON column session.add(MyTable(data={"first_name": "joseph",                           "last_name": "matthew", "age": "18"})) session.commit()  # Query the table using the JSON column result = (     session.query(MyTable)     .filter(MyTable .data["first_name"] == "joseph")     .all() )  for result in result:      print(result.id)  # prints 1 

Output:

The table is shown in Mysql CLi

Inserting Another Row 

In this example, we will be adding another row and querying all data from the tables. It adds another row to the table with a different JSON object containing first_name, last_name, and age, and commits the changes to the database. Then it queries all rows in the table and prints the id and data for each returned row.

Python
from sqlalchemy.orm import sessionmaker from Creation import engine, MyTable  # Create a session Session = sessionmaker(bind=engine) session = Session()  # Update the values into the table session.add(MyTable(data={"first_name": "martha",                           "last_name": "stuart", "age": "45"})) session.add(MyTable(data={"first_name": "boris",                           "last_name": "johnson", "age": "35"})) session.add(MyTable(data={"first_name": "vishal",                           "last_name": "kamat", "age": "25"})) session.commit()  # Query all rows in the table results = session.query(MyTable).all() for result in results:     print(result.id, result.data)  session.commit() 

Output:

Output of Update.py

Deleting Row

In this example, we will be deleting a row of data based on the id. This code deletes a row from the employee's table where the 'id' column is equal to 2. It then commits the changes to the database and closes the session. Below is the code for Deletion.py.

Python3
from sqlalchemy.orm import sessionmaker from Creation import engine, MyTable  # Create a session Session = sessionmaker(bind=engine) session = Session()  # Update the values into the table # Delete a row based on id session.query(MyTable).filter(MyTable.id == 2).delete() session.commit()   # Query all rows in the table results = session.query(MyTable).all() for result in results:     print(result.id, result.data)  session.commit() # closes the session here session.close() 

The Output for Deletion.py

 

Next Article
SQLAlchemy: How to group by two fields and filter by date

J

josephrvishal
Improve
Article Tags :
  • Technical Scripter
  • Python
  • Technical Scripter 2022
  • Python-SQLAlchemy
Practice Tags :
  • python

Similar Reads

  • SQLAlchemy Filter in List
    SQLAlchemy is a Python's powerful Object-Relational Mapper that, provides flexibility to work with Relational Databases. SQLAlchemy provides a rich set of functions that can be used in SQL expressions to perform various operations and calculations on the data using Python. In SQLAlchemy, we can filt
    4 min read
  • SQLAlchemy db.session.query()
    In SQLAlchemy, session.query() can be used as a filter in a query to specify criteria for which rows should be returned. This is done using the expression module and the filter method of the query object. The expression module allows you to create an expression that can be used in a query. This can
    5 min read
  • SQLAlchemy Group By With Full Child Objects
    In this article, we will explore how to use SQLAlchemy Group By With Full Child Objects in Python. SQLAlchemy provides several techniques to achieve SQLAlchemy Group By with Full Child Objects. SQLAlchemy Group By With Full Child ObjectsIn this section, we are making a connection with the database,
    9 min read
  • JSONB - Sqlalchemy
    One of the most well-liked relational database management systems (RDBMS) in the world, PostgreSQL is quite strong and allows developers access to a wide range of complex capabilities. One of the most useful features provided by Postgres is the support for JSON data types, together with the ability
    6 min read
  • SQLAlchemy: How to group by two fields and filter by date
    In this article, we will see how to group records by two fields and filter by date using SQLAlchemy in Python. Since we are going to use MySQL in this article, we will also install a SQL connector for MySQL in Python. However, none of the code implementations changes with change in the database exce
    3 min read
  • SQLAlchemy Core - Joins
    SQLAlchemy Core is a Python toolkit that enables developers to create complex database applications. It provides several features, one of which is the ability to join tables.  Joining tables allows developers to retrieve data from multiple tables simultaneously, which is useful when the data is rela
    3 min read
  • SQLAlchemy Core - Functions
    SQLAlchemy provides a rich set of functions that can be used in SQL expressions to perform various operations and calculations on the data. SQLAlchemy provides the Function API to work with the SQL functions in a more flexible manner. The Function API is used to construct SQL expressions representin
    7 min read
  • SQLAlchemy - Label
    SQLAlchemy is a Python library used for working with relational databases. It provides an intuitive way to interact with databases and allows us to write database-independent code. In this article, we'll explore one of the powerful features of SQLAlchemy called label(), which is used to add labels t
    4 min read
  • SQLAlchemy - Introduction
    SQLAlchemy is basically referred to as the toolkit of Python SQL that provides developers with the flexibility of using the SQL database. The benefit of using this particular library is to allow Python developers to work with the language's own objects, and not write separate SQL queries. They can b
    3 min read
  • Python SQLAlchemy - func.count with filter
    In this article, we are going to see how to perform filter operation with count function in SQLAlchemy against a PostgreSQL database in python Count with filter operations is performed in different methods using different functions. Such kinds of mathematical operations are database-dependent. In Po
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences