0

I have below data in JSON format, I have started with code below which throws a KEY ERROR.

Not sure how to get all data listed in headers section.

I know I am not doing it right in json_obj['offers'][0]['pkg']['Info']: but not sure how to do it correctly.

how can I get to different nodes like info,PricingInfo,Flt_Info etc?

{  
   "offerInfo":{  
      "siteID":"1",
      "language":"en_US",
      "currency":"USD"
   },
   "offers":{  
      "pkg":[  
         {  
            "offerDateRange":{  
               "StartDate":[  
                  2015,
                  11,
                  8
               ],
               "EndDate":[  
                  2015,
                  11,
                  14
               ]
            },
            "Info":{  
               "Id":"111"
            },
            "PricingInfo":{  
               "BaseRate":1932.6
            },
            "flt_Info":{  
               "Carrier":"AA"
            }
         }
      ]
   }
}

import os
import json
import csv


f = open('api.csv','w')
writer = csv.writer(f,delimiter = '~')
headers = ['Id' , 'StartDate', 'EndDate', 'Id', 'BaseRate', 'Carrier']
default = ''
writer.writerow(headers)

string = open('data.json').read().decode('utf-8')
json_obj = json.loads(string)

for pkg in json_obj['offers'][0]['pkg']['Info']:
        row = []
        row.append(json_obj['id']) # just to test,but I need column values listed in header section
        writer.writerow(row)
3
  • Maybe I am blind but I do not see anywhere the "hotelInfo" key in your json Commented Sep 15, 2015 at 20:58
  • My bad,corrected the right key name @Marco,but the problem still persist. Commented Sep 15, 2015 at 21:01
  • It's not really clear what you want to get ? just the id of each package? or you need other fields? Commented Sep 15, 2015 at 21:06

3 Answers 3

3

It looks like you're accessing the json incorrectly. After you have accessed json_obj['offers'], you accessed [0], but there is no array there. json_obj['offers'] gives you another dictionary.

For example, to get PricingInfo like you asked, access like this:

json_obj['offers']['pkg'][0]['PricingInfo']

or 11 from the StartDate like this:

json_obj['offers']['pkg'][0]['offerDateRange']['StartDate'][1]

And I believe you get the KEY ERROR because you access [0] in the dictionary, which since that isn't a key, you get the error.

Sign up to request clarification or add additional context in comments.

Comments

0

try to substitute this piece of code:

for pkg in json_obj['offers'][0]['pkg']['Info']:
        row = []
        row.append(json_obj['id']) # just to test,but I need column values listed in header section
        writer.writerow(row)

With this:

for pkg in json_obj['offers']['pkg']:
    row.append(pkg['Info']['Id'])
    year  = pkg['offerDateRange']['StartDate'][0]
    month = pkg['offerDateRange']['StartDate'][1]
    day   = pkg['offerDateRange']['StartDate'][2]
    StartDate = "%d-%d-%d" % (year,month,day)
    print StartDate
    writer.writerow(row)

2 Comments

It worked @Marco.. but why the StartDate comes as [2015,11,8],is there any way I can remove the [] and format to a proper YYYY-MM-DD string?
I have updated the answer to trasnform the date as you requested.
0

Try this

import os
import json
import csv

string = open('data.json').read().decode('utf-8')
json_obj = json.loads(string)


print json_obj["offers"]["pkg"][0]["Info"]["Id"]

print str(json_obj["offers"]["pkg"][0]["offerDateRange"]["StartDate"][0]) +'-'+ str(json_obj["offers"]["pkg"][0]["offerDateRange"]["StartDate"][1])+'-'+str(json_obj["offers"]["pkg"][0]
["offerDateRange"]["StartDate"][2])

print str(json_obj["offers"]["pkg"][0]["offerDateRange"]["EndDate"][0]) +'-'+ str(json_obj["offers"]["pkg"][0]["offerDateRange"]["EndDate"][1])+'-'+str(json_obj["offers"]["pkg"][0]
["offerDateRange"]["EndDate"][2])

print json_obj["offers"]["pkg"][0]["Info"]["Id"]

print json_obj["offers"]["pkg"][0]["PricingInfo"]["BaseRate"]

print json_obj["offers"]["pkg"][0]["flt_Info"]["Carrier"]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.