You split your problem into two steps. Reading and writing. In the first step you can check if `Aux``is in the keys already. If not you add it. Then you simply open the file to write and write the cleaned data to it:

import json

with open("record.json", "r") as infile:
    data = json.load(infile)
    for genre in data:
        for movie_genre in data[genre]:
            if "Aux" not in data[genre][movie_genre].keys():
                data[genre][movie_genre]["Aux"] = {"director": "MR J", "Producer": "Mr K"}

with open("record.json", "w") as outfile:
    outfile.write(json.dumps(data, indent=2))
Answer from k-nut on Stack Overflow
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!

🌐
DigitalOcean
digitalocean.com › community › tutorials › python-jsonpath-examples
Python JSONPath Examples | DigitalOcean
Technical tutorials, Q&A, events — This is an inclusive place where developers can find or lend support and discover new ways to contribute to the community.
🌐
Stack Overflow
stackoverflow.com › questions › 42918974 › python-json-find-parent-node-based-on-key
Python JSON find parent node based on key - Stack Overflow
I've got the following function which allows me to search through json and return the value of the key that is searched for. However, I'm trying to find the actual parentNode of the key being searched for and finding this a bit difficult. Copydef bar(somejson, key): def val(node): # Searches for the next Element Node containing Value e = node.nextSibling while e and e.nodeType != e.ELEMENT_NODE: e = e.nextSibling return (e.getElementsByTagName('string')[0].firstChild.nodeValue if e else None) # parse the JSON as XML foo_dom = parseString(xmlrpclib.dumps((json.loads(somejson),))) # and then search all the name tags which are P1's # and use the val user function to get the value return [val(node) for node in foo_dom.getElementsByTagName('name') if node.firstChild.nodeValue in key]
🌐
Linux Hint
linuxhint.com › search_json_python
How to search for data in JSON using python – Linux Hint
#!/usr/bin/env python3 # Import json module import json # Define json data applicants ="""{ "Scott C Aldridge": "Present", "Joe L Foss": "Present", "Clyde M Gold": "Present", "Monique C Doolittle": "Absent", "David M Volkert": "Present", "Israel M Oneal": "Present", "Elizabeth M Groff": "Absent" }""" # Initialize a counter counter = 0 # load the json data appList = json.loads(applicants) # iterate json to find the list of absent applicant for key in appList: if (appList[key] == 'Absent'): # Check the counter the print the message if (counter == 0): print("The following applicants are absent:") print(key) counter = counter + 1 # Print the message if no applicant is absent if (counter == 0): print("All applicants are present")
🌐
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 - Let’s see how to use a default value if the value is not present for a key. As you know, the json.loads method converts JSON data into Python dict so we can use the get method of dict class to assign a default value to the key if the value is missing.
🌐
W3Resource
w3resource.com › JSON › snippets › json-path-finder.php
JSON Path Finder
In this example, we use the jsonpath-ng library to find and extract specific data from a JSON structure. ... # Import necessary libraries import json from jsonpath_ng import jsonpath, parse # jsonpath for querying JSON # Define a JSON structure json_data = { "store": { "book": [ {"title": "Python Basics", "price": 10}, {"title": "Advanced Python", "price": 15} ], "bicycle": {"color": "red", "price": 100} } } # Create a JSONPath expression to find all book titles expression = parse("$.store.book[*].title") # Select all titles under store.book # Find matches for the expression in the JSON data matches = [match.value for match in expression.find(json_data)] # Print the extracted titles print(matches) # Output: ['Python Basics', 'Advanced Python']
Find elsewhere
Top answer
1 of 2
3

If you want the list of nodes used to reach the bottom id you could use the following:

def get_parent(json_tree, target_id):
    for element in json_tree:
        if element['id'] == target_id:
            return [element['id']]
        else:
            if element['child']:
                check_child = get_parent(element['child'], target_id)
                if check_child:
                    return [element['id']] + check_child

This creates a list when the id is matched, and then as it is passed back up the loops, adds the id for each level to the front of the list.

So, correcting your json to be proper (no trailing commas) and calling the function:

js = json.loads('[{"id": 1,"child": [{"id": 4,"child": []},{"id": 2,"child": [{"id": 37,"child": []},{"id": 39,"child": []}]},{"id": 3,"child": []}]},{"id": 120,"child": []},{"id": 121,"child": [{"id": 122,"child": []}]}]')

print(get_parent(js, 37))

prints

[1, 2, 37]
2 of 2
0

code.py:

import sys


TREE = [
    {
        "id": 1,
        "child": [
            {
                "id": 4,
                "child": [],
            },
            {
                "id": 2,
                "child": [
                    {
                        "id": 37,
                        "child": [],
                    },
                    {
                        "id": 39,
                        "child": [],
                    }
                ]
            },
            {
                "id": 3,
                "child": [],
            },
        ]
    },
    {
        "id": 120,
        "child": [],
    },
    {
        "id": 121,
        "child": [
            {
                "id": 122,
                "child": [],
            }
        ]
    }
]


def get_chain_ids(tree_dict, target_id, depth=0):
    cur_id = tree_dict["id"]
    if cur_id == target_id:
        yield cur_id
    else:
        yield_cur_id = False
        for child_dict in tree_dict["child"]:
            for child_id in get_chain_ids(child_dict, target_id, depth=depth + 1):
                yield_cur_id = True
                yield child_id
        if yield_cur_id:
            yield cur_id


if __name__ == "__main__":
    print("Python {:s} on {:s}\n".format(sys.version, sys.platform))

    for item in TREE:
        print("\nSearching tree (id: {:d})...".format(item["id"]))
        ids = get_chain_ids(item, 37)
        if (ids):
            for item in ids:
                print(item)

Notes:

  • Uses [Python]: Generators
  • The json (TEXT dict) was incorrect, I had to adjust it (besides formatting)
  • get_chain_ids takes the tree root (tree_dict) which is a dictionary, and target_id as arguments, and returns a generator yielding all the node ids from target_id to the root id
  • depth is currently not used
  • Since TREE is a list of nodes, I had to iterate over it and pass each element to the function
  • It doesn't handle cases where a node is malformed (lacks "id" or "child" keys, or if their values are not as expected)

Output:

(py35x64_test) E:\Work\Dev\StackOverflow\q048865303>"e:\Work\Dev\VEnvs\py35x64_test\Scripts\python.exe" code.py
Python 3.5.4 (v3.5.4:3f56838, Aug  8 2017, 02:17:05) [MSC v.1900 64 bit (AMD64)] on win32


Searching tree (id: 1)...
37
2
1

Searching tree (id: 120)...

Searching tree (id: 121)...
🌐
Scrapfly
scrapfly.io › blog › posts › parse-json-jsonpath-python
Introduction to Parsing JSON with Python JSONPath
April 10, 2026 - Master jsonpath python for extracting structured data from JSON APIs using advanced query expressions with array slicing, filtering, and recursive data lookup techniques. Implement JSONPath expressions with array slicing and wildcard matching for complex JSON data extraction · Use recursive data lookup techniques to find specific data points across nested JSON structures
🌐
Stack Overflow
stackoverflow.com › questions › 66550588 › get-the-child-node-data-from-json-file
python - Get the child node data from Json File - Stack Overflow
March 9, 2021 - js = { "Users": { "abcde": { "email": "[email protected]", "gender": "Male", "password": "123", "result": "Back Road Explorer", "username": "abcde" }, "halo": { "email": "[email protected]", "password": "halo", "result": "Outdoor Adventure", "username": "halo" }, "01": { "email": "[email protected]", "gender": "Male", "password": "dajcaq", "result": "Culinary Connoisseur", "username": "01" } } } def parse_json(js): usernames, results = [], [] for value in js['Users'].values(): usernames.append(value["username"]) results.append(value["result"]) usernames, results = ', '.join(usernames), ', '.join(results), print(f'username = {usernames}') print(f'result = {results}') ... Find the answer to your question by asking.
🌐
GeeksforGeeks
geeksforgeeks.org › working-with-json-data-in-python
Working With JSON Data in Python | GeeksforGeeks
June 3, 2022 - The text in JSON is done through quoted-string which contains the value in key-value mapping within { }. It is similar to the dictionary in Python. JSON shows an API similar to users of Standard Library marshal and pickle modules and Python natively supports JSON features.
Author: jabbalaci
🌐
Temboo
temboo.com › python › parsing-json
Parsing JSON in Python
Now you should to able to parse all sorts of JSON responses with our Python SDK. You can find lots of JSON responses to flex your parsing skills on in our Library.
🌐
DEV Community
dev.to › bluepaperbirds › get-all-keys-and-values-from-json-object-in-python-1b2d
Get all keys and values from json object in Python - DEV Community
January 12, 2021 - Using load function json file, this let me keep it into a variable called data. ... Then you have a Python object. Now you can get the keys and values. The code below depends on what your json file looks like.
🌐
W3Schools
w3schools.com › python › python_json.asp
Python JSON
JSON is text, written with JavaScript object notation. Python has a built-in package called json, which can be used to work with JSON data.