Getting Deeper Level JSON Values in Python
Question: I have a Python script that make an API call to retrieve data from Zendesk.
(Using Python 3.x) The JSON object has a structure like this:

    
    
    {
      "id":               35436,
      "url":              "https://company.zendesk.com/api/v2/tickets/35436.json",
      "external_id":      "ahg35h3jh",
      "created_at":       "2009-07-20T22:55:29Z",
      "updated_at":       "2011-05-05T10:38:52Z",
      "type":             "incident",
      "subject":          "Help, my printer is on fire!",
      "raw_subject":      "{{dc.printer_on_fire}}",
      "description":      "The fire is very colorful.",
      "priority":         "high",
      "status":           "open",
      "recipient":        "support@company.com",
      "requester_id":     20978392,
      "submitter_id":     76872,
      "assignee_id":      235323,
      "organization_id":  509974,
      "group_id":         98738,
      "collaborator_ids": [35334, 234],
      "forum_topic_id":   72648221,
      "problem_id":       9873764,
      "has_incidents":    false,
      "due_at":           null,
      "tags":             ["enterprise", "other_tag"],
      "via": {
        "channel": "web"
      },
      "custom_fields": [
        {
          "id":    27642,
          "value": "745"
        },
        {
          "id":    27648,
          "value": "yes"
        }
      ],
      "satisfaction_rating": {
        "id": 1234,
        "score": "good",
        "comment": "Great support!"
      },
      "sharing_agreement_ids": [84432]
    }
    

Where I am running into issues is in the `"custom_fields"` section
specifically. I have a particular custom field inside of each ticket I need
the value for, and I only want that particular value.

To spare you too many specifics of the Python code, I am reading through each
value below for each ticket and adding it to an output variable before writing
that output variable to a .csv. Here is the particular place the breakage is
occuring:

    
    
    output += str(ticket['custom_fields'][id:23825198]).replace(',', '')+',' 
    

All the replace nonsense is to make sure that since it is going into a comma
delimited file, any commas inside of the values are removed. Anyway, here is
the error I am getting:

    
    
        output += str(ticket['custom_fields'][id:int(23825198)]).replace(',', '')+','
    TypeError: slice indices must be integers or None or have an __index__ method
    

As you can see I have tried a couple different variations of this to try and
resolve the issue, and have yet to find a fix. I could use some help!

Thanks...


Answer: Are you using json.loads()? If so you can then get the keys, and do an if
statement against the keys. An example on how to get the keys and their
respective values is shown below.

    
    
    import json
    
    some_json = """{
    "id":               35436,
    "url":              "https://company.zendesk.com/api/v2/tickets/35436.json",
    "external_id":      "ahg35h3jh",
    "created_at":       "2009-07-20T22:55:29Z",
    "updated_at":       "2011-05-05T10:38:52Z",
    "type":             "incident",
    "subject":          "Help, my printer is on fire!",
    "raw_subject":      "{{dc.printer_on_fire}}",
    "description":      "The fire is very colorful.",
    "priority":         "high",
    "status":           "open",
    "recipient":        "support@company.com",
    "requester_id":     20978392,
    "submitter_id":     76872,
    "assignee_id":      235323,
    "organization_id":  509974,
    "group_id":         98738,
    "collaborator_ids": [35334, 234],
    "forum_topic_id":   72648221,
    "problem_id":       9873764,
    "has_incidents":    false,
    "due_at":           null,
    "tags":             ["enterprise", "other_tag"],
    "via": {
        "channel": "web"
    },
    "custom_fields": [
        {
        "sid":    27642,
        "value": "745"
        },
        {
        "id":    27648,
        "value": "yes"
        }
    ],
    "satisfaction_rating": {
        "id": 1234,
        "score": "good",
        "comment": "Great support!"
    },
    "sharing_agreement_ids": [84432]
    }"""
    
    # load the json object
    zenJSONObj = json.loads(some_json)
    
    # Shows a list of all custom fields
    print("All the custom field data")
    print(zenJSONObj['custom_fields'])
    print("----")
    # Tells you all the keys in the custom_fields
    print("How keys and the values")
    for custom_field in zenJSONObj['custom_fields']:
        print("----")
        for key in custom_field.keys():
            print("key:",key," value: ",custom_field[key])
    

You can then modify the JSON object by doing something like

    
    
    print(zenJSONObj['custom_fields'][0])
    zenJSONObj['custom_fields'][0]['value'] = 'something new'
    print(zenJSONObj['custom_fields'][0])
    

Then re-encode it using the following:

    
    
    newJSONObject = json.dumps(zenJSONObj, sort_keys=True, indent=4)
    

I hope this is of some help.

