Closed JamiesonDeuel closed 2 years ago
Hi,
I can't reproduce it. Here's the code:
import json
from asyncio import run
import aiofiles
async def amain():
async with aiofiles.open("db.json", "r") as f:
raw = await f.read()
data = json.loads(raw)
print(data)
run(amain())
and the data:
{"Card": {}}
Seems to work. Can you provide more info?
I am having this issue. If I read and write using regular "with open", everything is fine and works. Using aiofiles.open gives me an empty json file when I try to read it after writing to it:
import aiofiles
import asyncio
import json
async def amain():
data = {"test": "wow", "testing": "wowwww", "3": 4585}
result = await json_dump_to_file(data, "aiofiles_testing.json")
print(result)
async def json_dump_to_file(data, file_name) -> bool:
async with aiofiles.open("json\\temp.json", mode="w", encoding="utf-8") as f1:
json.dump(data, f1, indent=2, ensure_ascii=False)
f1.truncate()
await asyncio.sleep(10) # added this in case the file wasn't ready to be read or something
async with aiofiles.open("json\\temp.json", mode="r", encoding="utf-8") as f2:
raw = await f2.read()
if len(raw) > 0:
new_json = json.loads(raw)
else:
print("Error: Length of temp file was 0.")
return False
if new_json:
async with aiofiles.open(f"json\\{file_name}", mode="w", encoding="utf-8") as f3:
json.dump(new_json, f3, indent=2, ensure_ascii=False)
f3.truncate()
return True
print("new_json was None")
return False
asyncio.run(amain())
Maybe I'm making a mistake somewhere?
@veganburrito86 The json
module doesn't support aiofiles, since it's a Python module and aiofiles is a third-party library.
You have to use a diferent approach, like this:
import asyncio
import json
import aiofiles
async def amain():
data = {"test": "wow", "testing": "wowwww", "3": 4585}
async with aiofiles.open("test.json", "w") as f:
await f.write(json.dumps(data, indent=2, ensure_ascii=False))
asyncio.run(amain())
I am getting this error, json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0), when I try to read this json file. {"Card": {}}
when open this json file normal, I do not get this error.