2021年1月3日星期日

Appending into an empty JSON file in python

I already have a JSON file which I am parsing using Python 2.7 and I want to dump the parsed out data into another empty JSON file. I am using a for-loop to parse out the data from the old JSON file and at the same time within that loop I want to append to that new JSON file. My original JSON file is in the form of a JSON array. Note: The new JSON file will have the same keys as the old JSON file i.e I am just parsing out the data according to the if-condition and then inserting the whole index (that satisfies the condition) from the old JSON to the new JSON. Old JSON = "output_log.json" New JSON = "cumulative_output.json"

The new JSON file would be a list of indexes for eg something like this:

[{"name":".....", "commit":".....", "author":"...", "title":"...", "body":"..."},  {"name":".....", "commit":".....", "author":"...", "title":"...", "body":"..."},  .........  ]  
    with open("output_log.json", 'r') as f:          json_ob = json.load(f)                  for index in range(len(json_ob)):              if (bool(re.search(r"\s", json_ob[index]['name']))) is True and ('444' in json_ob[index]['title']) and ('https://robotics.com/projects/' in json_ob[index]['body']):                  with open('cumulative_output.json', 'a') as f:                      entry = {'name': json_ob[index]['name'], 'commit': json_ob[index]['commit'], 'author': json_ob[index]['author'], 'title': json_ob[index]['title'], 'body': json_ob[index]['body']}                      f.write(entry)                      f.write(",")  
https://stackoverflow.com/questions/65556852/appending-into-an-empty-json-file-in-python January 04, 2021 at 10:05AM

没有评论:

发表评论