Home > Enterprise >  Get data for JSON Python second List
Get data for JSON Python second List

Time:10-22

Hoping you are good I am trying to get data from zendisk by API and Python Json i can get any data Value under Audits LikeTicket_id and auther_id but when tried get data under Events such as Body keep get this error

print(audit['body'])

KeyError: 'body'

JSON Output

{
   "audits":[
      {
         "id":1727876301271,
         "ticket_id":54010951,
         "created_at":"2021-10-21T10:58:06Z",
         "author_id":12306596687,
         "metadata":{
            "system":{
               "client":"GuzzleHttp/6.2.1 curl/7.29.0 PHP/7.1.2",
               "ip_address":"x.x.x.x",
               "location":"Boardman, OR, United States",
               "latitude":45.8491,
               "longitude":-119.7143
            },
            "custom":{
               
            }
         },
         "events":[
            {
               "id":1727876301291,
               "type":"Comment",
               "author_id":366289833251,
               "body":"Sehr geehrte Damen und Herren,\n\nIn unserer Bestellung fehlt das Kleid, es war nicht mit dabei, obwohl es hätte drin sein müssen.\nFreundliche Grüße",
            
               "attachments":[
                  
               ],
               "audit_id":1727876301271
            },
            {
               "id":1727876301311,
               "type":"Create",
               "value":"366289833251",
               "field_name":"requester_id"
            },

Python Code

import requests
import csv
# Settings
auth = 'xxxxxxx', 'xxxxxx'
view_tickets = []
view_id = 214459268
view_audits = []
ticket_id = 54010951
view_events =[]
print(f'Getting tickets from ticket_id ID {ticket_id}')
url = f'https://xxxx.zendesk.com/api/v2/tickets/54010951/audits.json'
while url:
    response = requests.get(url, auth=auth)
    page_data = response.json()
    audits = page_data['audits']     # extract the "tickets" list from the page
    view_audits.extend(audits)
    url = page_data['next_page']


for audit in audits:

    print(audit['body'])

CodePudding user response:

You know you're overwriting, not adding, to audits right? (in this line: audits = page_data['audits']). I don't think that makes sense, but it's hard to know your intent.

To fix the error itself, your json structure has the body key inside the events key. So you can access it with:

print(audit['events'][0]['body'])

or, using another loop:

for audit in audits:
    for event in audit['events']
        print(event['body'])

You might get an error for the 2nd one because it doesn't appear to have the body key. You can add an if statement to handle that if you want.

  • Related