lucanello
lucanello

Reputation: 85

Update JSON file in Python

The .json file I want to update has this structure:

{
  "username": "abc",
  "statistics": [
    {
      "followers": 1234,
      "date": "2018-02-06 02:00:00",
      "num_of_posts": 123,
      "following": 123
    }
  ]
}

and I want it to insert a new statistic like so

{
  "username": "abc",
  "statistics": [
    {
      "followers": 1234,
      "date": "2018-02-06 02:00:00",
      "num_of_posts": 123,
      "following": 123
    },
    {
      "followers": 2345,
      "date": "2018-02-06 02:10:00",
      "num_of_posts": 234,
      "following": 234
    }
  ]
}

When working with

with open(filepath, 'w') as fp:
    json.dump(information, fp, indent=2)

the file will always be overwritten. But I want the items in statistics to be added. I tried reading the file in many possible ways and append it afterwards but it never worked.

The data is coming written in the information variable just like

information = {
  "username": username,
  "statistics": [
      {
          "date": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
          "num_of_posts": num_of_posts,
          "followers": followers,
          "following": following
      }
  ]
}

So how do I update the .json file that my information is added correctly?

Upvotes: 4

Views: 17953

Answers (4)

Dave Brown
Dave Brown

Reputation: 1

You could use this function:

def append_statistics(filepath, num_of_posts, followers, following):
    new_statistics_record={
        "date": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
        "num_of_posts": num_of_posts,
        "followers": followers,
        "following": following
    }

    with open(filepath, 'r') as fp:
        information = json.load(fp)

    information["statistics"].append(new_statistics_record)

    with open(filepath, 'w') as fp:
        json.dump(information, fp, indent=2)

Upvotes: 0

Saad Saadi
Saad Saadi

Reputation: 1061

You need to read the .json file and then append the new dataset and dump that data. See the code.

import json
appending_statistics_data = {}

appending_statistics_data["followers"] =  2346
appending_statistics_data["date"] = "2018-02-06 02:10:00"
appending_statistics_data["num_of_posts"] =  234
appending_statistics_data["following"] = 234

with open(file.json, 'r') as fp:
    data = json.load(fp)

data['statistics'].append(appending_statistics_data)    
#print(json.dumps(data,indent=4))               


with open(file.json, 'w') as fp:
    json.dump(data, fp, indent=2)

Upvotes: 0

Jesper
Jesper

Reputation: 1649

You would want to do something along the lines of:

def append_statistics(filepath, num_of_posts, followers, following):

    with open(filepath, 'r') as fp:
        information = json.load(fp)

    information["statistics"].append({
        "date": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
        "num_of_posts": num_of_posts,
        "followers": followers,
        "following": following
    })

    with open(filepath, 'w') as fp:
        json.dump(information, fp, indent=2)

Upvotes: 7

Kevin Liu
Kevin Liu

Reputation: 737

Normally, you don't directly update the file that you are reading from.

You might consider:

  1. read from source file.
  2. do processing
  3. write to a new temp file
  4. close both source file and temp file
  5. rename (move) the temp file back to source file

Upvotes: -1

Related Questions