first, your input isn't json. Json uses double quotes. But suppose you successfully loaded it with json, it's now a dictionary, called d.

Then you can scan all sub-dicts of d and test serial key against your value, stopping when found using any and a generator comprehension:

print(any(sd['serial']=='00000000762c1d3c' for sd in d['device']))

returns True if serial found False otherwise.

Answer from Jean-François Fabre on Stack Overflow
🌐
W3Schools
w3schools.com › python › python_json.asp
Python JSON
Python has a built-in package called json, which can be used to work with JSON data. ... If you have a JSON string, you can parse it by using the json.loads() method.
Discussions

How to find JSON object in text with python - Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most. Learn more about Collectives ... Connect and share knowledge within a single location that is structured and easy to search. Learn more about Teams ... I'm trying to parse JSON object from text with python regex. I found this match: ... See the regex match in ... More on stackoverflow.com
🌐 stackoverflow.com
January 17, 2019
How to find and replace a specific string in a json file with python - Post.Byes
With a python program, I saved a ics file to a json one.The json file contains calendar info. My purpose is to replace a few specific strings (hours) by different ones (Keywords). basically 8:00 to Meeting1 ; 9:00 to Meeting 2 and so on. The Json content looks something like this "11/18/21 ... More on post.bytes.com
🌐 post.bytes.com
Find a value in JSON using Python - Stack Overflow
I’ve previously succeeded in parsing data from a JSON file, but now I’m facing a problem with the function I want to achieve. I have a list of names, identification numbers and birthdate in a JSON.... More on stackoverflow.com
🌐 stackoverflow.com
python - Parsing json and searching through it - Stack Overflow
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. More on stackoverflow.com
🌐 stackoverflow.com
🌐
Reddit
reddit.com › r/learnpython › easy way to extract json part of a string?
r/learnpython on Reddit: easy way to extract json part of a string?
January 12, 2022 -

Hi

I have a string that contains a lot of text, and then a json part. Is there an easy way to extract only the json part? or is substring the way to go? (im just having truble with it cutting off some of the brackets).

The output is a powershell script, that looks up some data in a exchange server, and then outputs the object a json string. But it also outputs some text on how the script has run, so i want to remove that part. (i have been unable to supress that part)

Top answer
1 of 3
2
The correct move here is to edit the Powershell script to remove that output. That being said, consider that if you find the beginning of the JSON object, you can then pass the remaining string to json.loads. It will then raise a JSONDecodeError , which contains the position of where the error occured. So you slice the string one more time and try again. Result: import json def parse_json_garbage(s): s = s[next(idx for idx, c in enumerate(s) if c in "{["):] try: return json.loads(s) except json.JSONDecodeError as e: return json.loads(s[:e.pos]) In the REPL: >>> parse_json_garbage(""" ... this is a bunch of crap, ignore this please ... More crap ... ayylmao ... { ... "foo" : "bar", ... "baz" : "quux" ... } ... More crap goes here! ... """) {'foo': 'bar', 'baz': 'quux'}
2 of 3
2
It depends on the structure of the string. There is no good magic way for a function to look at a string and say "Hmmmm, this part is valid JSON," and toss the rest away. But if you, using your human intelligence, can identify a pattern in the output that is always true, then you can leverage that pattern to extract "the json part" and decode it. So say for instance that the script you're running has output like this: my-script.py Quote of the day: "The truth is rarely pure and never simple." -Oscar Wilde Weather: { "wind": "10 mph NNE", "clouds": null, "precipitation": null, "temperature": "47 Fahrenheit" } Winning lottery numbers: 3, 7, 22, 23, 41, 42, 43 Then you might say "Ah-ha, the valid JSON part starts after the string "Weather:" and ends just before the string "Winning lottery numbers". You might then write code that looks something like this: import json data = """ Quote of the day: "The truth is rarely pure and never simple." -Oscar Wilde Weather: { "wind": "10 mph NNE", "clouds": null, "precipitation": null, "temperature": "47 Fahrenheit" } Winning lottery numbers: 3, 7, 22, 23, 41, 42, 43 """ # Or however you're capturing the output of the script. start_pos = data.find('Weather:') + len('Weather:') # .find() will return the BEGINNING of the match, so you'll need to account for the length of the string you're searching for end_post = data.find('Winning lottery numbers') json_chunk = data[start_pos:end_pos] data_dictionary = json.loads(json_chunk) data_dictionary will then be a standard Python dictionary that you can you standard dictionary techniques to examine, print, change, write to disk, etc. When you're talking about breaking down terminal output, it's often easy to find a pattern that always applies in more or less the style above, though of course it's unlikely that you'll be dealing with output EXACTLY like that. If you can't, though, and you really just need to try paring down a string until it "looks like JSON," your problem is much harder, because "looks like JSON" is a human-type description that you'll have to find a way to translate into a form that the Python interpreter can understand.
🌐
YouTube
youtube.com › codeflare
find string in json python - YouTube
Download this code from https://codegive.com Title: Finding a String in JSON using Python: A Step-by-Step TutorialIntroduction:JSON (JavaScript Object Notati...
Published   January 21, 2024
Views   56
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-extract-or-parse-json-from-a-string-in-python
How to Parse JSON String in Python - GeeksforGeeks
September 16, 2025 - We will be using Python’s json module, which offers several methods to work with JSON data. In particular: json.loads(): Converts a JSON string s into a Python object (dict or list).
🌐
Linux Hint
linuxhint.com › search_json_python
How to search for data in JSON using python – Linux Hint
Here, a variable named customerData is defined to store the JSON data. The value of the key will be taken as input from the user. loads() method of JSON module is used to load JSON data in the variable named customer. Next, ‘in’ operator is used to search the key.
Top answer
1 of 3
40

You found a regex that uses syntax that Python standard library re module doesn't support.

When you look at the regex101 link, you'll see that the pattern works when using the PRCE library, and the problematic (?R) syntax that throws the error uses a feature called recursion. That feature is only supported by a subset of regex engines.

You could install the regex library, an alternative regex engine for Python that explicitly does support that syntax:

>>> import regex
>>> pattern = regex.compile(r'\{(?:[^{}]|(?R))*\}')
>>> pattern.findall('''\
... This is a funny text about stuff,
... look at this product {"action":"product","options":{...}}.
... More Text is to come and another JSON string
... {"action":"review","options":{...}}
... ''')
['{"action":"product","options":{...}}', '{"action":"review","options":{...}}']

Another option is to just try and decode any section that starts with { using the JSONDecoder.raw_decode() method; see How do I use the 'json' module to read in one JSON object at a time? for an example approach. While the recursive regex can find JSON-like text, the decoder approach would let you extract only valid JSON text.

Here is a generator function that does just that:

from json import JSONDecoder

def extract_json_objects(text, decoder=JSONDecoder()):
    """Find JSON objects in text, and yield the decoded JSON data

    Does not attempt to look for JSON arrays, text, or other JSON types outside
    of a parent JSON object.

    """
    pos = 0
    while True:
        match = text.find('{', pos)
        if match == -1:
            break
        try:
            result, index = decoder.raw_decode(text[match:])
            yield result
            pos = match + index
        except ValueError:
            pos = match + 1

Demo:

>>> demo_text = """\
This is a funny text about stuff,
look at this product {"action":"product","options":{"foo": "bar"}}.
More Text is to come and another JSON string, neatly delimited by "{" and "}" characters:
{"action":"review","options":{"spam": ["ham", "vikings", "eggs", "spam"]}}
"""
>>> for result in extract_json_objects(demo_text):
...     print(result)
...
{'action': 'product', 'options': {'foo': 'bar'}}
{'action': 'review', 'options': {'spam': ['ham', 'vikings', 'eggs', 'spam']}}
2 of 3
4

If there is only one JSON in one line, you can use the index methods to find the first and the last bracket to select the JSON:

firstValue = jsonString.index("{")
lastValue = len(jsonString) - jsonString[::-1].index("}")
jsonString = jsonStringEncoded[firstValue:lastValue]
🌐
Python Examples
pythonexamples.org › python-parse-json-string-example
How to Parse JSON String in Python?
In this example, we are given a JSON string, where the data in the JSON string is an array of elements. We shall use json.loads() function to parse this JSON String. The Python equivalent of a JSON Array is a Python List.
Find elsewhere
🌐
Zyte
zyte.com › home › blog › json parsing with python [practical guide]
A Practical Guide to JSON Parsing with Python
July 6, 2023 - In JSON, data is typically stored in either an array or an object. To access data within a JSON array, you can use array indexing, while to access data within an object, you can use key-value pairs.
🌐
Real Python
realpython.com › python-json
Working With JSON Data in Python – Real Python
August 20, 2025 - Later in the tutorial, you’ll ... it’s time to find out how you can work with JSON data in Python. ... Python supports the JSON format through the built-in module named json. The json module is specifically designed for reading and writing strings formatted as ...
🌐
Post.Byes
post.bytes.com › home › forum › topic › python
How to find and replace a specific string in a json file with python - Post.Byes
This is the python program that parses the ics file into a json one : ... from datetime import datetime, timedelta, timezone import icalendar from dateutil.rrule import * f = open('myschool.json', 'w') def parse_recurrences(recur_rule, start, exclusions): """ Find all reoccuring events """ rules = rruleset() first_rule = rrulestr(recur_rule, dtstart=start) rules.rrule(first_rule) if not isinstance(exclusions, list): exclusions = [exclusions] for xdate in exclusions: try: rules.exdate(xdate.dts[0].dt) except AttributeError: pass now = datetime.now(timezone.utc) this_year = now + timedelta(days=
🌐
Programiz
programiz.com › python-programming › json
Python JSON: Read, Write, Parse JSON (With Examples)
In this tutorial, you will learn to parse, read and write JSON in Python with the help of examples. Also, you will learn to convert JSON to dict and pretty print it.
🌐
regex101
regex101.com › library › sjOfeq
regex101: Find JSON strings in a string
Python · Golang · Java 8 · .NET 7.0 (C#) Rust · Sponsors · There are currently no sponsors. Become a sponsor today! Search among 15,000 community submitted regex patterns... Your search did not match anything · 1 · / \{ # { character (?: # non-capturing group [^{}] # anything that is not a { or } | # OR (?R) # recurses the entire pattern )* # previous group zero or more times \} # } character ·
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-program-to-extract-a-single-value-from-json-response
Python program to extract a single value from JSON response - GeeksforGeeks
July 23, 2025 - Load the JSON data into a variable using the Python load() function. Now, get the value of keys in a variable. Now convert the value of the dictionary into a list and slice the string using the split function.
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'
Top answer
1 of 2
1
import json
import sys
import os
data = []
if os.stat("data.txt").st_size != 0 :
    file = open('data.txt', 'r')
    data = json.load(file)
    print(data)

choice = input("What's your choice ?")
if choice == 'a':
    # Add a new joke.
    # See Point 3 of the "Requirements of admin.py" section of the assignment brief.
    jokeSetup = input('Enter setup of joke: ')
    jokePunchLine = input('Enter punchline of joke: ')
    entry = {'setup': jokeSetup , 'punchline': jokePunchLine}
    data.append(entry)
    file = open('data.txt', 'w')
    json.dump(data, file)
    file.close()
    print('Joke Added.')
    pass


elif choice == 's':
    # Search the current jokes.
    # See Point 5 of the "Requirements of admin.py" section of the assignment brief.
    searchTerm = input('Enter search term: ')
    file = open('data.txt', 'r')
    data = json.load(file)
    file.close()

    for sub_dict in data:
        if searchTerm in sub_dict['setup']:
            print(sub_dict['punchline'])
    pass
# or you could modify the last for loop, like this:
    for dict in data:
        if searchTerm in dict['setup'] or searchTerm in dict['punchline']:
            print('found!')
    pass
2 of 2
1

You could do it like this:

if choice == 'a':
# Add a new joke.
# See Point 3 of the "Requirements of admin.py" section of the assignment brief.
    jokeSetup = input('Enter setup of joke: ')
    jokePunchLine = input('Enter punchline of joke: ')
    entry = {'setup': jokeSetup , 'punchline': jokePunchLine}
    data.append(entry)
    file = open('data.txt', 'w')
    json.dump(data, file)
    file.close()
    print('Joke Added.')
    pass

elif choice == 's':
    # Search the current jokes.
    # See Point 5 of the "Requirements of admin.py" section of the assignment brief.
    searchTerm = input('Enter search term: ')
    file = open('data.txt', 'r')
    data = json.load(file)
    file.close()

    for item in data[0].items():
        if searchTerm in str(item[1]):
            print ('found it')

    pass

# or the for loop could be like this
for sub_dict in data:
    if searchTerm in sub_dict['setup'] or searchTerm in sub_dict['punchline']:
        print('found!')
🌐
ReqBin
reqbin.com › code › python › g4nr6w3u › python-parse-json-example
How to parse a JSON with Python?
Nested JSON objects will also be processed and included in the dictionary (see example below). To parse a JSON file, use the json.load() paired method (without the "s"). In this Python Parse JSON example, we convert a JSON data string into a Python object.
🌐
Stack Overflow
stackoverflow.com › questions › 50986671 › searching-json-file-for-string-python › 50986951
regex - Searching JSON file for string - Python - Stack Overflow
@doctorlove:corrected title: i added client:AP in order to distinguish client, i run 2 REST API calls and need,for each client to send email with CC-XXXX and client code ... The requests module can decode JSON for you. Use data=response.json(). Otherwise, use the standard json module. Don't try to parse a JSON string or file yourself.
🌐
Stack Overflow
stackoverflow.com › questions › 72565438 › how-can-i-get-a-string-from-json-in-python
How can I get a string from JSON in Python? - Stack Overflow
I have this JSON content: {'status': '1', 'message': 'OK', 'result': {'LastBlock': '14934113', 'SafeGasPrice': '119', 'ProposeGasPrice': '119', 'FastGasPrice': '119', 'suggestBaseFee': '118.1745901...