如何从Python创建多个JSON文件

2024-10-02 12:22:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要从Python创建多个JSON文件,例如:

[{
  'commentParentId': 'abcdedf',
  'parentId': '123456',
  'posted': '28/02/2019',
  'author': {
    'id': '125379',
    'name': 'david',
    'email': 'abc@gmail.com
   },
  'content': 'i need help'
  },
  {
  'commentParentId': 'abcdedf',
  'parentId': '253654',
  'posted': '28/02/2019',
  'author': {
    'id': '458216',
    'name': 'david',
    'email': 'abc@gmail.com
   },
  'content': 'i need help'
  },
  ........................
}]

示例:我有10个注释,每个注释的id不同,我想用每个注释创建10个JSON文件。1个JSON文件有1个JSON对象和JSON名称的作者id

但在Python中,要在JSON文件中写入数据,我使用:

^{pr2}$

我不知道如何编写10个JSON文件,每个文件名都是id。我是Python新手,JSON,谢谢你的帮助。在


Tags: 文件namecomidjsonemailcontentgmail
2条回答

使用for语句迭代注释并将其写入文件。在

for comment in comments:
    filename = f'/tmp/author_{comment["author"]["id"]}.json'
    with open(filename, "w", encoding="utf-8") as writeJSON:
        json.dump(comment, writeJSON, ensure_ascii=False)

怎么样:

import json

with open('scrapercomment.json', 'r') as src:
    parsed_json = json.load(src)
    for comment in parsed_json:
        f = open(comment['author']['id'], 'w')
        f.write(str(comment))
        f.close()

相关问题 更多 >

    热门问题