DenverDave
DenverDave

Reputation: 45

How to extract specific value from json data that is now a dictionary

I am working on a tool to download a list of open cases from my corporate CRM tool. I have the code to pull them down and into a file. The format of the file is:

{
"result": [
      {
         "active":"true",
         "number":"case_123",
         "state":"Open",
         "customer":"",
         "priority":"3 - Moderate",
         "assigned_to":"me",
         "product":"My Product",
         "contact_time_zone":"",
         "opened_at":"23/07/2020 11:10:08",
         "closed_at":""
      },
      "<more cases>"
   ],
}

I want to extract all values for the key "number".

I tried to follow some of the suggestions given when you type in the subject of the post. This one seemed close: How to extract specific data from JSON?

But did not work.

Here is the code:

    import json
    print("Started Reading JSON file")
    with open("sn_data.json", "r", encoding='utf-8') as read_file:
    print("Converting JSON encoded data into Python dictionary")
    developer = json.load(read_file)

    print(developer['result']['number'])

This throws: print(developer['result']['number']) TypeError: list indices must be integers or slices, not str

I have confirmed that I have a dictionary using print(type(developer)).

If I comment out the print above and use:

    for number in developer.items():
    print(developer.items["number"])

I get: print(developer.items["number"]) TypeError: 'builtin_function_or_method' object is not subscriptable

I look up the errors and find no real answers. As I am not a full time Python developer, just support guy trying to help out.

Upvotes: 0

Views: 1740

Answers (2)

devintark
devintark

Reputation: 76

The value for "result" key in your dictionary is a list, so you can't index into it with ['number']. 'number' is a key in a dictionary in that list.

result: [{}.{}...]

So you have to iterate over it. Each item in that list is a dict, so you can then iterate into it with ['result']

for result in developer['result']:
    print(result['number'])

In your second block of code you store a value in a variable called number, but then you use a string "number" to access it. That is not the same thing just FYI. Still, dict.items() will return a list and you cant access it like a dict either.

Upvotes: 1

Countour-Integral
Countour-Integral

Reputation: 1154

You should be using developer['result'][0]['number']. Your variable Developer is a dictionary and the key you want, result is a list of 1 element (as we can see), so you'll have to first reference the dictionary key (developer) then the index (0 or whatever it is) and then the other dictionary's key number

Upvotes: 0

Related Questions