簡體   English   中英

如何從Python創建多個JSON文件

[英]How to create multiple JSON files from 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個注釋,其中10個id不同,我想分別創建10個JSON文件。 1個JSON文件具有1個JSON對象和JSON名稱的作者ID。

但是在Python中,我使用以下命令將數據寫入JSON文件:

with open("scrapercomment.json", "w", encoding="utf-8") as writeJSON:

    json.dump(data, writeJSON, ensure_ascii=False)

我不知道如何編寫10個JSON文件,每個名稱是每個id。 我是Python JSON新手,非常感謝您的幫助。

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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM