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.
JavaScript
x
4
1
thing1
2
thing2
3
thing3
4
I would like to iterate this list and return matches from the JSON file
JavaScript
1
13
13
1
{
2
"ssb": [
3
{
4
"uid": 27,
5
"appid": "thing1",
6
"title": "Title of thing",
7
"created_time": "2009-11-17T01:32:28+00:00",
8
"published_time": "2009-11-17T01:32:28+00:00",
9
"updated_time": "2022-11-14T17:26:23+00:00",
10
}
11
]
12
}
13
JavaScript
1
23
23
1
import json
2
3
upgrade_apps = open("apps_to_upgrade.txt", "r")
4
ua = upgrade_apps.readlines()
5
upgrade_apps.close()
6
ua3 = "thing1"
7
8
#Testing results
9
print(ua)
10
print(type(ua))
11
for atu in ua:
12
print(atu)
13
## ^ this returns the expected text from file
14
15
with open('dump.json') as f:
16
data = json.load(f)
17
f.close()
18
jsonResult = data['ssb']
19
for i in jsonResult:
20
if i['appid'] == ua3: #<THIS IS WHERE I AM STUCK> If i use ua3 OR "thing1" i get the expected result
21
print(i['uid'],i['appid'])
22
break
23
I have also tried including a for loop before the first for loop. I get back only the last entry in the text file.
JavaScript
1
12
12
1
#all of the above codeblock plus
2
3
for atu in ua:
4
with open('dump.json') as f:
5
data = json.load(f)
6
f.close()
7
jsonResult = data['ssb']
8
for i in jsonResult:
9
if i['appid'] == atu:
10
print(i['uid'],i['appid'])
11
break
12
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.
JavaScript
1
14
14
1
import json
2
3
with open("apps_to_upgrade.txt", "r") as upgrade_apps
4
ua = set(line.strip() for line in upgrade_apps)
5
6
with open('dump.json') as f:
7
data = json.load(f)
8
9
jsonResult = data['ssb']
10
for i in jsonResult:
11
if i['appid'] in ua:
12
print(i['uid'],i['appid'])
13
break
14