Search code examples
pythonjsonpython-trio

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.


Solution

  • 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.