0

I need to create multiple JSON files from Python, for example:

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

The example: I have 10 comments with 10 id different and I want to create 10 JSON files with each. 1 JSON file has 1 JSON object and JSON name's author id.

But in Python, to write data in JSON file I use:

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

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

I don't have an idea of how to write 10 JSON files with each name is each id. I'm a newbie Python, JSON so thanks for your help.

2
  • So, how it's related to Selenium? Commented Feb 28, 2019 at 10:41
  • Before I asking, I think 2 ways to create multiple JSON files. First way: When I completed scraper 1 comment I will create JSON files. It means I don't add 10 comments in a list like my post. Second way: I add 10 comments in a list and I write JSON files. I write: 'Scraper comments with Selenium ' because I want to everyone know my data not necessarily like my post. I will delete now, so thanks for your help to edit my post become clearly Commented Feb 28, 2019 at 11:48

2 Answers 2

3

Use for statement to iterate over comments and writing it a file.

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)
Sign up to request clarification or add additional context in comments.

1 Comment

that amazing, i just think is a name of file, we cann't change automatic just can change when we input from keyboard. Thanks for help.
0

How about :

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.