Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (19.9k points)

I'm reading the contents of a JSON text file and am struggling to get the contents of a specific index in the data.

An example of the data objects I'm reading is below. There are multiple instances in my file, but they all look similar to the following:

[{ "value": "hello", "name": "janedoe", "istrue": "yes", "number": 5 }]

The console returns nothing every time and I can print json_list[0] and it returns the whole value {'name': 'janedoe', 'number': 5}.

I would like to use the substring "doe" to search within the list and find a match and then return the index of that match.

I have tried using a function and one liners such as this

res = [i for i in json_list if substring in i] 

    with open ('text.txt', 'r') as output_file:

        json_array = json.load(output_file)

        json_list = []

        json_list = [{'name': item['name'].split('.')[0], 'number': item['number']}

    for item in json_array]

    substring = 'doe'

    def index_containing_substring(json_list, substring):

        for i, s in enumerate(json_list):

            if substring in s:   

                return i

        return -1                                                 

I would like to return the index value so that I can then call that index and utilize its data.

1 Answer

0 votes
by (25.1k points)

Just loop over your list_of_dicts and for each dict check if string "doe" is present in it its name key. If so then return the index, like this:

def find_doe_in_list_of_dicts(list_of_dicts):

    for dictionary in list_of_dicts:

        if "doe" in dictionary["name"]:

            index_of_item_with_doe = list_of_dicts.index(dictionary)

            break

    return index_of_item_with_joe

Related questions

0 votes
1 answer
asked Jul 29, 2019 in Python by Rajesh Malhotra (19.9k points)
+3 votes
2 answers
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Jan 30, 2021 in Python by laddulakshana (16.4k points)

Browse Categories

...