JSON File update 2 values without break its structure or other values

Question:

Hello I have the next code to try to update a JSON file:

with open('orderprepare.json', 'r') as f:
    finalorder = json.load(f)


finalorder['ItemList']['Quantity'] = 500

with open('orderprepare.json', 'w') as f:
    json.dump(finalorder, f)

But it shows the error “finalorder[‘ItemList’][‘Quantity’] = 500 TypeError: list indices must be integers or slices, not str”.

What I want to update is exactly without break the structure of the JSON file including brackets [], {}.

I want to keep the structure but what I want to modify is:

*In ‘ItemList’ I want to modify ‘Quantity’ to 500

*In ‘BillTo’ I want to modify to ‘PostalCode’ to 90011

How can be modified the code, as I said, without breaking the structure and just leaving like it is the JSON file but just that two values updated?

This is the JSON file:

{
   {
   "OrderNumber": "443435",
   "OrderDate": "2028-07-15 209:35:22.000",
   "ExpectedShipService": "FedEx",
   "ShipTo": {
      "CustomerName": "testtest",
      "Phone": "000-000-0000",
      "Address1": "testtest",
      "Address2": "null",
      "City": "testtest",
      "StateOrProvince": "MA",
      "PostalCode": "37879",
      "Country": "USA"
   },
   "BillTo": {
      "CustomerName": "testtest",
      "Address1": "testtest",
      "Address2": "null",
      "City": "testtest",
      "StateOrProvince": "MA",
      "PostalCode": 100,
      "Country": "USA"
   },
   "ItemList": [
      {
         "ItemNumber": "testtest",
         "BuyerPartNumber": "tetst",
         "Quantity": 6,
         "UnitPrice": 20.49
      }
   ]
}

I tried the code above with the JSON file above explained.

Asked By: Alex Co

||

Answers:

This is how your new assignment should look like:

finalorder['ItemList'][0]['Quantity'] = 500
finalorder['BillTo']['PostalCode'] = 90011
Answered By: Dev_Van

If you look closely you’ll notice that the key ‘ItemList’ you’re trying to access is actually holding a value of type list and not a dictionary. You need to access the element that is inside that list (which is the dictionary you wanna modify) before you try to update it’s value.

This is what you should do:

finalorder['ItemList'][0]['Quantity'] = 500

For the other one, you can simply do this:

finalorder['BillTo']['PostalCode'] = 90011

Also, the JSON you provided seems to have an extra opening curly bracket. You might wanna look into that.

Answered By: Mohsin Ali
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.