I want to fetch all the respective ID's from the given text file but it is giving me empty list. kindly help me in this.
with open('json-data.txt') as f:
content = f.read()
#print(content)
runners = []
for index in range(len(content)):
for key in content[index]:
if key == 'active' and content[index][key] == True:
runners.append(content[index]['id'])
print(runners)
Output:
[]
Where is this data from? It mentions json, but it's not in json format. It's a python expression, so you could just eval() it, but if you don't control the data, that's not a safe thing to do.
Do you need to parse everything? If you just need the ID numbers, a regular expression is sufficient.
import re
text = open("json-data.txt").read()
print(re.findall(r"'id':\s*(\d+)", text))
Output:
['5', '25', '112']
If I want to parse the text data here, how should I do it then?
Why is the file called "json"? Did it start out life as a JSON file? If so, it would be much easier to just read it that way.
(Jan-19-2022, 07:42 AM)bowlofred Wrote: [ -> ]Why is the file called "json"? Did it start out life as a JSON file? If so, it would be much easier to just read it that way.
I am saving the data of the link in the text file that is the reason why I am calling it as 'Json-data'.may be that is the reason why it is
creating ambiguity.
As bowlofred already said: if it's json you should save it as .json and use Python built-in tools for parsing.
However, if you have no control over input data/files then you can use
ast.literal_eval() to safely evaluate an expression node or a string containing a Python literal or container display.
from ast import literal_eval
with open('literal_values.txt', 'r') as f:
data = literal_eval(f.read())
ids = [record['id'] for record in data if record['active']]
print(ids)
Output:
[5, 25]