Python Forum
value null when update in json file
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
value null when update in json file
#1
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 } ]
Reply
#2
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.
Reply
#3
(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
Reply
#4
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.
3lnyn0 likes this post
Reply
#5
(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" }
Reply
#6
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.
Reply
#7
Not to mention a value like "$3,000.00" is obviously a string, not an int.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  encrypt data in json file help jacksfrustration 1 190 Mar-28-2024, 05:16 PM
Last Post: deanhystad
  parse json field from csv file lebossejames 4 725 Nov-14-2023, 11:34 PM
Last Post: snippsat
  Python Script to convert Json to CSV file chvsnarayana 8 2,495 Apr-26-2023, 10:31 PM
Last Post: DeaD_EyE
  Loop through json file and reset values [SOLVED] AlphaInc 2 2,092 Apr-06-2023, 11:15 AM
Last Post: AlphaInc
  How to express null value klatlap 3 854 Mar-25-2023, 10:40 AM
Last Post: klatlap
  Converting a json file to a dataframe with rows and columns eyavuz21 13 4,395 Jan-29-2023, 03:59 PM
Last Post: eyavuz21
  How to read csv file update matplotlib column chart regularly SamLiu 2 1,058 Jan-21-2023, 11:33 PM
Last Post: SamLiu
  validate large json file with millions of records in batches herobpv 3 1,260 Dec-10-2022, 10:36 PM
Last Post: bowlofred
  Writing to json file ebolisa 1 995 Jul-17-2022, 04:51 PM
Last Post: deanhystad
  Trying to parse only 3 key values from json file cubangt 8 3,446 Jul-16-2022, 02:05 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020