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

其他-Python中的JSON解析帮助

(其他 - JSON Parsing help in Python)

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

我下面有JSON格式的数据,我从下面的代码开始,该代码抛出KEY ERROR

不确定如何获取标题部分中列出的所有数据。

我知道我没有正确执行此操作,json_obj['offers'][0]['pkg']['Info']:但不确定如何正确执行操作。

我如何到达不同的节点,例如info,PricingInfo,Flt_Info等?

{  
   "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
11
Marco 2015-09-17 03:25:11

尝试替换这段代码:

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)

有了这个:

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)