Dec-28-2021, 05:27 PM
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.
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!!!') continueI 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
}
]