You have to iterate over the list of dictionaries and search for the one with the given id_number. Once you find it you can print the rest of its data and break, assuming id_number is unique.

data = [
 {
   "id_number": "SA4784",
   "name": "Mark",
   "birthdate": None
 },
 {
   "id_number": "V410Z8",
   "name": "Vincent",
   "birthdate": "15/02/1989"
 },
 {
   "id_number": "CZ1094",
   "name": "Paul",
   "birthdate": "27/09/1994"
 }
]

for i in data:
    if i['id_number'] == 'V410Z8':
        print(i['birthdate'])
        print(i['name'])
        break

If you have control over the data structure, a more efficient way would be to use the id_number as a key (again, assuming id_number is unique):

data =  { "SA4784" : {"name": "Mark", "birthdate": None},
          "V410Z8" : { "name": "Vincent", "birthdate": "15/02/1989"},
          "CZ1094" : {"name": "Paul", "birthdate": "27/09/1994"}
        }

Then all you need to do is try to access it directly:

try:
    print(data["V410Z8"]["name"])
except KeyError:
    print("ID doesn't exist")
>> "Vincent"
Answer from DeepSpace on Stack Overflow
🌐
Reddit
reddit.com › r/learnpython › how can i search through a json file i loaded and find a specific value?
r/learnpython on Reddit: How can I search through a json file I loaded and find a specific value?
August 5, 2022 -

I have a very big json file that I have loaded into my script. Each item has many keys each with a unique value.

I am interested in only one key, 'filename' so I need to ignore all other keys. A user will input a query in an input prompt and if the value exists as a filename then it returns another value associated with a different key.

To illustrate here is an example of the json:

[
    {
        'filename': 'file1',
        'size': '56B'
        'id': '1'
    },
    
    {
        'filename': 'file2',
        'size': '100B'
        'id': '2'
    },

    {
        'filename': 'file3',
        'size': '1KB'
        'id': '3'
    }
]           

and the user inputs the query 'file3'

How would I get the script to search only the filename keys for the matching string 'file3' and when it finds it, it needs to return the value '3' corresponding to the id key in the same entry?

🌐
Linux Hint
linuxhint.com › search_json_python
How to search for data in JSON using python – Linux Hint
The following script shows steps on searching the value of a particular key in the nested JSON data. Here, a nested JSON variable named nestedData is declared to store nested data. This script will search the brand name of the women watch. #!/usr/bin/env python3 # Import json module import json # Define json variable of nested data nestedData = """{ "watch":{ "men":{ "brand":"Titan", "price":200 }, "women":{ "brand":"Citizen", "price":250 }, "kid":{ "brand":"Blancpain", "price":100 } } }""" # Load the json data watchlist = json.loads(nestedData) # Search 'brand' for women if 'brand' in watchlist['watch']['women']: print(watchlist['watch']['women']['brand'])
🌐
Claudia Kuenzler
claudiokuenzler.com › blog › 1395 › how-to-iterate-nested-json-dict-search-specific-value-print-key-python
How to iterate through a nested JSON, search for a specific value and print the key with Python
February 27, 2024 - While I was working on a Python script, I needed to find a way to iterate through a nested JSON (which is actually a dict inside Python), search for a specific field (key) and if the value of this key meets a condition, print the parent (top layer) key.
🌐
Reddit
reddit.com › r/learnpython › best method to query and search json in python?
r/learnpython on Reddit: Best method to query and search JSON in Python?
April 6, 2022 -

I'm doing a fair amount of work with APIs. Usually I need to take the response and then output to a CSV then search through it for specific data and possibly manipulate it. Trying to search the JSON itself for a specific key value has proven more difficult than I expected. Is there an easier way to do this? Am I just making this harder than it needs to be?

🌐
DEV Community
dev.to › r_elena_mendez_escobar › efficiently-querying-json-data-in-python-exploring-the-met-museums-artworks-31fj
Efficiently Querying JSON Data in Python: Exploring the MET Museum's Artworks - DEV Community
October 17, 2024 - 🛠️ Conversion to Lowercase (_func_to_lower): This function allows us to convert any string of text to lowercase, which is useful for standardizing comparisons between values. 🛠️ Search with Regular Expressions (_func_contains_regex): With this function, we can search for patterns within text strings using regular expressions. This is particularly helpful when we want to identify artworks that contain specific terms or patterns in their descriptions, titles, or tags. JMESPath is a powerful query language for JSON, but it has certain limitations in its native functions.
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › python › working-with-json-data-in-python
Working With JSON Data in Python - GeeksforGeeks
It allows you to extract specific values from complex or nested JSON structures in a clean and readable way. For example, in normal Python access, you might retrieve a nested value like this: doc["person"]["age"]. JMESPath simplifies such queries, ...
Published: April 28, 2026
🌐
Medium
medium.com › @artijs › searching-values-in-json-using-python-a4badf5fa76a
Searching values in JSON using Python | by Arthur J | Medium
December 2, 2023 - Data is stored in a structured format in JSON and many a times we come across use cases to select or search a specific value from a large file. A json file is made up of key-value pair. We shall use JSON module in python to understand and search inside a file.
🌐
PYnative
pynative.com › home › python › json › python check if key exists in json and iterate the json array
Python Check if key exists in JSON and iterate the JSON array
May 14, 2021 - Check if the key exists or not in JSON using Python. Check if there is a value for a key. Return default value if the key is missing in JSON. Iterate JSON array in Python.
🌐
Python Guides
pythonguides.com › json-data-in-python
How to Extract Values from a JSON Array in Python
April 27, 2026 - Learn to get values from a JSON array in Python. We cover the json module, list comprehensions, and handling nested data with real-world USA business examples.
Top answer
1 of 5
35

ObjectPath is a library that provides ability to query JSON and nested structures of dicts and lists. For example, you can search for all attributes called "foo" regardless how deep they are by using $..foo.

While the documentation focuses on the command line interface, you can perform the queries programmatically by using the package's Python internals. The example below assumes you've already loaded the data into Python data structures (dicts & lists). If you're starting with a JSON file or string you just need to use load or loads from the json module first.

import objectpath

data = [
    {'foo': 1, 'bar': 'a'},
    {'foo': 2, 'bar': 'b'},
    {'NoFooHere': 2, 'bar': 'c'},
    {'foo': 3, 'bar': 'd'},
]

tree_obj = objectpath.Tree(data)

tuple(tree_obj.execute('$..foo'))
# returns: (1, 2, 3)

Notice that it just skipped elements that lacked a "foo" attribute, such as the third item in the list. You can also do much more complex queries, which makes ObjectPath handy for deeply nested structures (e.g. finding where x has y that has z: $.x.y.z). I refer you to the documentation and tutorial for more information.

2 of 5
29

As json.loads simply returns a dict, you can use the operators that apply to dicts:

>>> jdata = json.load('{"uri": "http:", "foo", "bar"}')
>>> 'uri' in jdata       # Check if 'uri' is in jdata's keys
True
>>> jdata['uri']         # Will return the value belonging to the key 'uri'
u'http:'

Edit: to give an idea regarding how to loop through the data, consider the following example:

>>> import json
>>> jdata = json.loads(open ('bookmarks.json').read())
>>> for c in jdata['children'][0]['children']:
...     print 'Title: {}, URI: {}'.format(c.get('title', 'No title'),
                                          c.get('uri', 'No uri'))
...
Title: Recently Bookmarked, URI: place:folder=BOOKMARKS_MENU(...)
Title: Recent Tags, URI: place:sort=14&type=6&maxResults=10&queryType=1
Title: , URI: No uri
Title: Mozilla Firefox, URI: No uri

Inspecting the jdata data structure will allow you to navigate it as you wish. The pprint call you already have is a good starting point for this.

Edit2: Another attempt. This gets the file you mentioned in a list of dictionaries. With this, I think you should be able to adapt it to your needs.

>>> def build_structure(data, d=[]):
...     if 'children' in data:
...         for c in data['children']:
...             d.append({'title': c.get('title', 'No title'),
...                                      'uri': c.get('uri', None)})
...             build_structure(c, d)
...     return d
...
>>> pprint.pprint(build_structure(jdata))
[{'title': u'Bookmarks Menu', 'uri': None},
 {'title': u'Recently Bookmarked',
  'uri':   u'place:folder=BOOKMARKS_MENU&folder=UNFILED_BOOKMARKS&(...)'},
 {'title': u'Recent Tags',
  'uri':   u'place:sort=14&type=6&maxResults=10&queryType=1'},
 {'title': u'', 'uri': None},
 {'title': u'Mozilla Firefox', 'uri': None},
 {'title': u'Help and Tutorials',
  'uri':   u'http://www.mozilla.com/en-US/firefox/help/'},
 (...)
}]

To then "search through it for u'uri': u'http:'", do something like this:

for c in build_structure(jdata):
    if c['uri'].startswith('http:'):
        print 'Started with http'
🌐
GitHub
github.com › s1s1ty › py-jsonq
GitHub - s1s1ty/py-jsonq: A simple Python package to Query over Json Data · GitHub
endswith : Check if the value of given key in data ends with (has a suffix of) the given value. This would only works for String type data. contains : Same as in · case_insensitive -- if True, the search will be case insensitive, False is default. example: Let's say you want to find the 'users' who has id of 1. You can do it like this: qu = JsonQ(file_path).at('users').where('id', '=', 1).get() You can add multiple where conditions.
Author: s1s1ty
🌐
Zyte
zyte.com › home › blog › json parsing with python [practical guide]
JSON Parsing with Python [Practical Guide]
December 3, 2024 - 1import json 2import jmespath 3 4json_string = '{"numbers": [1, 2, 3], "car": {"model": "Model X", "year": 2022}}' 5json_data = json.loads(json_string) 6 7# Accessing nested JSON 8name = jmespath.search('car.model', json_data) # Result: Model X 9 10# Taking the first number from numbers 11first_number = jmespath.search('numbers[0]', json_data) # Result: 1 ... Those examples only display the basics of what JMESPath can do. JMESPath queries can also filter and transform JSON data. For example, you can use JMESPath to filter a list of objects based on a specific value or to extract specific parts of an object and transform them into a new structure.
🌐
GeeksforGeeks
geeksforgeeks.org › python-program-to-extract-a-single-value-from-json-response
Python program to extract a single value from JSON response - GeeksforGeeks
September 25, 2024 - Import JSON from the modules. Open the JSON file in read-only mode using the Python with() function. Load the JSON data into a variable using the Python load() function. Now, get the value of keys in a variable.
Top answer
1 of 9
35

As I said in my other answer, I don't think there is a way of finding all values associated with the "P1" key without iterating over the whole structure. However I've come up with even better way to do that which came to me while looking at @Mike Brennan's answer to another JSON-related question How to get string objects instead of Unicode from JSON?

The basic idea is to use the object_hook parameter that json.loads() accepts just to watch what is being decoded and check for the sought-after value.

Note: This will only work if the representation is of a JSON object (i.e. something enclosed in curly braces {}), as in your sample.

from __future__ import print_function
import json

def find_values(id, json_repr):
    results = []

    def _decode_dict(a_dict):
        try:
            results.append(a_dict[id])
        except KeyError:
            pass
        return a_dict

    json.loads(json_repr, object_hook=_decode_dict) # Return value ignored.
    return results

json_repr = '{"P1": "ss", "Id": 1234, "P2": {"P1": "cccc"}, "P3": [{"P1": "aaa"}]}'
print(find_values('P1', json_repr))

(Python 3) output:

['cccc', 'aaa', 'ss']
2 of 9
15

I had the same issue just the other day. I wound up just searching through the entire object and accounted for both lists and dicts. The following snippets allows you to search for the first occurrence of a multiple keys.

import json

def deep_search(needles, haystack):
    found = {}
    if type(needles) != type([]):
        needles = [needles]

    if type(haystack) == type(dict()):
        for needle in needles:
            if needle in haystack.keys():
                found[needle] = haystack[needle]
            elif len(haystack.keys()) > 0:
                for key in haystack.keys():
                    result = deep_search(needle, haystack[key])
                    if result:
                        for k, v in result.items():
                            found[k] = v
    elif type(haystack) == type([]):
        for node in haystack:
            result = deep_search(needles, node)
            if result:
                for k, v in result.items():
                    found[k] = v
    return found

deep_search(["P1", "P3"], json.loads(json_string))

It returns a dict with the keys being the keys searched for. Haystack is expected to be a Python object already, so you have to do json.loads before passing it to deep_search.

Any comments for optimization are welcomed!