简体   繁体   中英

Searching in a .txt file (JSON format) for a particular string and then printing a specific key

I have to take input from the user in the form of strings and then have to search for it in a .txt file which is in JSON format. If the text matches, X has to be done otherwise Y. For example if the user enters 'mac' my code should display the complete name(s) of the terms which contains the search term 'mac'.

My JSON file has currently Big Mac as an item and when I search for 'mac' it shows nothing, whereas, it has to display me (0 Big Mac). 0 is the index number which is also required.

  if option == 's':
        if 'name' in open('data.txt').read():
            sea = input ("Type a menu item name to search for: ")
            with open ('data.txt', 'r') as data_file:
                data = json.load(data_file)
            for line in data:
                if sea in line:
                    print (data[index]['name'])
                else:
                    print ('No such item exist')
        else:
            print ("The list is empty")
            main()

I have applied a number of solutions but none works.

See How to search if dictionary value contains certain string with Python .

Since you know you are looking for the string within the value stored against the 'name' key, you can just change:

if sea in line

to:

if sea in line['name']

(or if sea in line.get('name') if there is a risk that one of your dictionaries might not have a 'name' key).

However, you're attempting to use index without having set that up anywhere. If you need to keep track of where you are in the list, you'd be better off using enumerate :

for index, line in enumerate(data):
    if sea.lower() in line['name'].lower():
        print ((index, line['name']))

If you want 'm' to match 'Big Mac' then you will need to do case-insensitive matching ('m' is not the same as 'M'). See edit above, which converts all strings to lower case before comparing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM