Script to load JSON file and create a condition to end or continue with the code

Question:

Hello I call a JSON file with the next code:

with open('C:/ftpfiles/itemdatasku.json') as json_file:
    data = json.load(json_file)

What I want to do is create an exception if “list_no” doesn’t exist, or has other information then the script must close. If exists continue in the code working.

try:
    x = data['results']['list_no']
    print("exists")
except KeyError:
    sys.exit()
    print("not exists")

It doesn’t work. This routine I took from other sample JSON file but here not works. The error it gives is:

TypeError: list indices must be integers or slices, not str

This is the JSON file:

{
  "count": 1,
  "next": null,
  "previous": null,
  "results": [
    {
      "list_no": "0000",
      "item_no": "3435",
      "upc_code": "",
      "manufacturer_no": "564556-00",
      "manufacturer": "SAMSUNGOEM",
      "category": "SSD",
      "product_name": "Samsung PM9A1 - SSD - 256 GB - PCIe 4.0 x4 (NVMe)",
      "price": 56.65,
      "instant_rebate": "",
      "instant_rebate_item_no": "",
      "weight": 0.06,
      "unit": 300,
      "length": 14.75,
      "width": 12,
      "height": 3.75,
      "package": "BULK",
      "specorder": "Y",
      "is_domestic_only": "N",
      "inventory": {
        "": 55
      }
    }
  ]
}

This is an example how the JSON file can be if not exist the “list_no”:

{"count": 0, "next": null, "previous": null, "results": []}
Asked By: Alex Co

||

Answers:

data['results'] is a list, not a dictionary. What you want is data['results'][0]['list_no']:

try:
    list_no = data['results'][0]['list_no']
    print("exists")
except (KeyError, IndexError, TypeError):
    print("not exists")
    sys.exit()
Answered By: Hai Vu
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.