简体   繁体   English

Python三重奏,在循环内保存JSON

[英]Python trio, Saving JSON under loop within

Currently, am receiving a dict within my rec function coming from the receiver channel.目前,我正在接收来自接收方频道的rec function 中的命令。

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.我不确定这是否算作将 JSON 转储到 for 循环下的文件中的正确方法。 Please advise if there's more Pythonic way for that.请告知是否有更多 Pythonic 方式。

Well, one improvement to make this code somewhat-more-pythonically-correct is to re-order the if count … test thus:好吧,使这段代码更符合 Python 标准的一项改进是重新排序if count …测试如下:

    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.因为那里没有重要的 JSON 流媒体模块 AFAIK,我会以基本相同的方式编写这段代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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