Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JSON read as a string and cannot use data as a list

There are many questions related to json files here but somehow I’m not finding the answer to my issue.

I’ve dumped that data into a json_books.json file:

[{"title": "Pavot et mémoire", "author": ["Paul Celan"], "tags": ["Poésie"], "publisher": "Christian Bourgois", "pubdate": 1992}, {"title": "De seuil en seuil", "author": ["Paul Celan"], "tags": ["Poésie"], "publisher": "Christian Bourgois", "pubdate": 1991},  
{"title": "The 4 Disciplines of Execution: Achieving Your Wildly Important Goals", "author": ["Chris McChesney, Sean Covey, Jim Huling"], "tags": ["Business & Economics", "Management", "Self-Help", "Personal Growth", "Success", "Leadership"], "publisher": "Simon and Schuster", "pubdate": 2012},  
{"title": "Apprendre à finir", "author": ["Laurent Mauvignier"], "tags": ["Roman"], "publisher": "Les Editions de Minuit", "pubdate": 2004},  
//...]

EDIT:
To dump it, I used:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

json_books = json.dumps(books, ensure_ascii=False)

with open('json_books.json', 'w') as outfile:
    json.dump(json_books, outfile, ensure_ascii=False)

–end edit–

So this is stored as a string. When I decode it with

with open('json_books.json') as file:
    books = json.loads(file.read())

Books is still only a string. But I’d like it to be a list.
If I try to decode without the read() function I get this error :

TypeError: the JSON object must be str, bytes or bytearray, not TextIOWrapper

And if I try to decode it with load(file) it is still just a string. So I cannot do anything with it.

Would someone know how I convert this back into a list ?

>Solution :

After you decode json file as string by

with open('json_books.json') as file:
    books = json.loads(file.read())

Then convert it to list by

books = json.loads(books)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading