Reputation: 5
I have to create a login system for a whole bunch of students, where the data is provided by a text file in the following format:
[
{
"clave": "f22LwdI",
"alumno": "SI",
"nombre": "Samuel Riquelme"
},
{
"clave": "KaEEkNjFz",
"alumno": "NO",
"nombre": "Paulina Toro",
}
]
I've tried several text reading functions without success. So that's why I decided to bring this here.
In this case I need to instantiate 2 different users and read the file in order to make this possible.
Upvotes: 0
Views: 48
Reputation: 46849
you could try this:
from ast import literal_eval
# or read that string in from the file with something like
# with open('filename.txt', 'r') as file:
# strg = file.read()
strg = '''[ { "clave": "f22LwdI", "alumno": "SI", "nombre": "Samuel Riquelme" },
{ "clave": "KaEEkNjFz", "alumno": "NO", "nombre": "Paulina Toro", } ]'''
lst = literal_eval(strg)
print(lst[0]['clave'])
note that the returned object is a list of dictionaries.
now that the formatting of your question has been updated: your format is (almost) json; if you correct the superfluous comma at the end of the second dictionary you could do this:
import json
strg = '''[
{
"clave": "f22LwdI",
"alumno": "SI",
"nombre": "Samuel Riquelme"
},
{
"clave": "KaEEkNjFz",
"alumno": "NO",
"nombre": "Paulina Toro"
}
]'''
lst = json.loads(strg)
print(lst)
print(lst[1])
Upvotes: 2