Skip to content
Advertisement

find value in JSON from list in text file

What I am trying to accomplish: Use contents of a text file to search for values in JSON file.

My text file contains one entry per line. The will match values in the JSON file.

thing1
thing2
thing3

I would like to iterate this list and return matches from the JSON file

{
  "ssb": [
    {
      "uid": 27,
      "appid": "thing1",
      "title": "Title of thing",
      "created_time": "2009-11-17T01:32:28+00:00",
      "published_time": "2009-11-17T01:32:28+00:00",
      "updated_time": "2022-11-14T17:26:23+00:00",
     }
   ]
 }
import json

upgrade_apps = open("apps_to_upgrade.txt", "r")
ua = upgrade_apps.readlines()
upgrade_apps.close()
ua3 = "thing1"

#Testing results
print(ua)
print(type(ua))
for atu in ua:
    print(atu)
##  ^ this returns the expected text from file

with open('dump.json') as f:
    data = json.load(f)
f.close()
jsonResult = data['ssb']
for i in jsonResult:
    if i['appid'] == ua3: #<THIS IS WHERE I AM STUCK> If i use ua3 OR "thing1" i get the expected result
        print(i['uid'],i['appid'])
        break

I have also tried including a for loop before the first for loop. I get back only the last entry in the text file.

#all of the above codeblock plus

for atu in ua:
    with open('dump.json') as f:
        data = json.load(f)
    f.close()
    jsonResult = data['ssb']
    for i in jsonResult:
        if i['appid'] == atu:
            print(i['uid'],i['appid'])
            break

Advertisement

Answer

Remove the newlines from the lines in ua, and turn it into a set. Then you can test if i['appid'] is in the set.

import json

with open("apps_to_upgrade.txt", "r") as upgrade_apps
    ua = set(line.strip() for line in upgrade_apps)

with open('dump.json') as f:
    data = json.load(f)

jsonResult = data['ssb']
for i in jsonResult:
    if i['appid'] in ua:
        print(i['uid'],i['appid'])
        break
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement