Home > Software design >  JSON read as a string and cannot use data as a list
JSON read as a string and cannot use data as a list

Time:08-12

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:

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 ?

CodePudding user response:

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)

CodePudding user response:

Ok it took me an hour to see it but my issue was easy.

Instead of

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

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

I just did

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

And it works.

Indeed the first dumps is converting my data into string, so it is read back as a string.

  • Related