Python Forum

Full Version: value null when update in json file
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi!
I have 4 functions, one for adding a new item to the json file, one for building a new dictionary, one for validating the data I enter from the keyboard, and one for updating one or more fields in the existing json file.
My problem is when I try to update a field in json, the value is NULL.

def update_product():
    with open('proiect\products.json') as f:
        val = json.load(f)
    print('The names of the products in the list are:')
    for element in val:
        print(f'    ',element['name'])
    #I scroll through the json file and display only the name

    product_name = input('Enter the name of product: ')
    print("Info for this product are:")
    for el in val:
        if el['name'] == product_name:
            for key, value in el.items():
                if key != 'name':
                    print('element {key}   -> value {value}'.format(key=key, value=value))
    #I enter a name from the keyboard and display the other fields

    modify = input('Insert the item you want to modify:')
    #I ask the user what name they want to change
    for el in val: 
        if el['name'] == product_name:   
            for key, value in el.items():
  
                if modify in key:
                    value = validation(key)
                    el.update({key:value})
                    with open('proiect\products.json', 'w') as f:
                        json.dump(val, f)

def validation(info):
    if info == 'stock':
        while True:
            product_dict[info] = input(f'Please enter the {info}: ')
            if product_dict[info].isdigit():
                break
            else:
                print('Invalid format!!!')
                continue
I tried to modify the stock, it was 12, after modification it should be 100 but it is null.

Output:
{ "product_id": "32131312", "name": "iphone x", "producer": "iphone", "price": 5000, "stock": null } ]
You are trying to use the output of validation() (line 25), but that function always returns None (because it has no explicit return statement).

You need to either have the validation program return data, or your caller needs to get the data out of product_dict, which is where validation seems to be updating. That isn't in your code that you've pasted, so I only assume it's some global defined and used elsewhere.
(Dec-28-2021, 06:27 PM)bowlofred Wrote: [ -> ]You are trying to use the output of validation() (line 25), but that function always returns None (because it has no explicit return statement).

You need to either have the validation program return data, or your caller needs to get the data out of product_dict, which is where validation seems to be updating. That isn't in your code that you've pasted, so I only assume it's some global defined and used elsewhere.

Product_dict is in function is the function with which you added a new dictionary in json file

def add_products(name):
    replies = ['yes', 'no']
    reply = 'X'

    while not reply in replies:
        reply = input('Enter yes to continue, enter no to stop ')
        if reply == 'yes':
            answers = get_product_data(name)
            product_data.append(answers)
            break
        elif reply == 'no':
            operate_menu(main_menu)


        # file_path = 'proiect\products.json'
    if os.path.getsize('proiect\products.json') == 0:
        with open('proiect\products.json', 'w', encoding='utf-8') as f:
            json.dump(product_data, f)
        print('Product successfully added!')
    else:
        with open('proiect\products.json') as f:
            val = json.load(f)

        val.append(answers)
        with open('proiect\products.json', 'w') as f:
            json.dump(val, f)
        print('Product successfully added!')

def get_product_data(name):
    global products

    for info in name:
        if info == 'product_id':
            validation('product_id')
        if info == 'name':
            validation('name')
        if info == 'producer':
            validation('producer')
        if info == 'category':
            validation('category')
        if info == 'price':
            validation('price')
        if info == 'stock':
            validation('stock')

    return product_dict
As bowlofred says, your problem is this:
value = validation(key)
Which is going to set value = None because validation() does not have a return statement and thus returns the default value None. You can modify validation to return a value, or you can get the value some other way.
(Dec-29-2021, 05:16 PM)deanhystad Wrote: [ -> ]As bowlofred says, your problem is this:
value = validation(key)
Which is going to set value = None because validation() does not have a return statement and thus returns the default value None. You can modify validation to return a value, or you can get the value some other way.

I solved this problem. Thansk!

I have another question, do you have any idea why price, stock and product id when I write them in the json file I write them as str not as int. If I display them before writing to the file, it displays them as int but the problem occurs after I write them to the json file.

Output:
{ "product_id": "5235325252352", "name": "Aspire 5", "producer": "Acer", "category": "phone", "price": "$3,000.00", "stock": "19" }
They are strings in the json file because they are strings in your program. input() returns a string and I don't see anywhere in your code were you convert the strings to numbers. I don't know what you mean by "display them", but if you are printing the values, print does not place quotes around strings, so "19" would be printed as 19.
Not to mention a value like "$3,000.00" is obviously a string, not an int.