Warm tip: This article is reproduced from serverfault.com, please click

JSON Parsing help in Python

发布于 2015-09-15 20:52:53

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)
Questioner
rkj
Viewed
0
Marco 2015-09-17 03:25:11

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)