skip to Main Content

I’m sorry for the crazy title. I’m new to programming and have no idea what I’m doing.

I’m making a weight tracker that saves data to a JSON.
The data is a nested dictionary that supposed to look like:

{
    "Dates": {
        "11/11/11": {
            "Morning": 500,
            "Night": 502
            
        }
    }
}

I’ve been trying to make the tracker ask for date input, and use that input as a new value for the "Dates" key aslong as the date doesnt already exist, and if it does exist to then append new values to the Morning or Night keys based on user input.

Here is my code:

weight_date_dict = open('main.json')

today = input("Enter the date(MM/DD/YY): ")

data = json.loads(weight_date_dict.read())

if today not in data:
    data['Dates'] = today

answer = input("Morning or Night? (Case sensitive): ")
if answer == "Morning":
    m_weight = input("Weight? ")
    #ERROR: Cant index a string('Dates') with a string(today)
    data['Dates'][today]['Morning'] = m_weight
elif answer == "Night":
    n_weight = input("Weight? ")
    data['Dates'][today]['Night'] = n_weight
else:
    print("Please enter Morning or Night.")

After solving how to write to the json without overwriting the previous dictionary keys/values inside of it, I added:

if today not in data:
    data['Dates'] = today
    data['Dates'][today] = {'Morning': None, 'Night': None}

to add a new date, which came up with "TypeError: ‘str object does not support item assignment’"

The line data['Dates'][today]['Morning'] = m_weight, which is supposed to append a new value to the Morning or Night keys, doesnt work because strings can’t be indexed by strings.

And I cant figure out how to append values to a date that already exists since its user-inputted. I feel like I’m completely off on how to do this.

2

Answers


  1. You should check for the date in the subobject identified by the "Dates" key, and set it to an empty object if it doesn’t exist yet.

    if today not in data['Dates']:
        data['Dates'][today] = {}
    

    In addition, you need to convert the user input from str to int.

    m_weight = int(input("Weight? "))
    # ...
    n_weight = int(input("Weight? "))
    

    Finally, use json.dump to write the updated version to the file at the end of the program.

    with open('main.json', 'w') as f:
        json.dump(data, f, indent=4)
    
    Login or Signup to reply.
  2. Your code has a few issues:

    First,

    if today not in data:
        data['Dates'] = today
    

    doesn’t do what you think it does. today not in data checks if today exists in data, but all your actual data is in data['Dates']. Also, by doing data['Dates'] = today, you overwrite all that data. What you really want to do is this:

    today = input("Enter the date(MM/DD/YY): ")
    if today not in data['Dates']:
        data['Dates'][today] = {}
    

    That’s why you get the error later on when you try to do data['Dates'][today]. data['Dates'] is no longer a dictionary of your data, its a string of today’s date.

    Your code also has a few other issues, such as not converting user input from a string to an integer. I also made some changes to reduce the code and make it a bit cleaner. Here’s the full code that I got working for you:

    import json
    
    data = None
    with open('main.json') as f:
        data = json.loads(f.read())
    
    today = input("Enter the date(MM/DD/YY): ")
    if today not in data['Dates']:
        data['Dates'][today] = {}
    
    answer = input("Morning or Night? (Case sensitive): ")
    weight = int(input("Weight? "))
    data['Dates'][today]['Morning'] = weight
    
    with open('main.json', 'w') as f:
        json.dump(data, f)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search