简体   繁体   中英

Python trio, Saving JSON under loop within

Currently, am receiving a dict within my rec function coming from the receiver channel.

async def rec(receiver):
    with open('data.json', 'w', encoding='utf-8', buffering=1) as f:
        f.write('[\n')
        async with receiver:
            count = 0
            async for val in receiver:
                count += 1
                if count != 1:
                    f.write(',')
                json.dump(val, f, indent=4, ensure_ascii=False)
        print(f'[*] - Active items: {count}')
        f.write('\n]')

am not sure if that's count as the correct way to dump JSON into a file under a for loop. Please advise if there's more Pythonic way for that.

Well, one improvement to make this code somewhat-more-pythonically-correct is to re-order the if count … test thus:

    async with receiver:
        count = 0
        async for val in receiver:
            if count:
                f.write(',')
            count += 1
            json.dump(val, f, indent=4, ensure_ascii=False)

Also, you might want to pass the file name in as a parameter, and add a linefeed after the comma.

As there's no non-trivial JSON streamer module out there AFAIK, I'd write this code mostly the same way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM