使用带有多个词典的python解析JSON

时间:2016-10-20 05:33:22

标签: python json

我试图使用python -

解析以下json
{
   "sentAt":"2016-06-11T04:48:25Z",
   "Device":"iPhone6",
   "batch":[
      {
         "URL":"/laundry/Vanish",
         "event":"PageView",
         "createdAt":"2016-06-11T04:47:58Z"
      },
      {
         "listPrice":6.5,
         "product_id":47446,
         "category":"",
         "salePrice":5.2,
         "eventName":"ViewProduct",
         "prodName":"Vanish",
         "createdAt":"2016-06-11T04:47:59Z"
      }
   ]
}

我能够使用下面的python代码解析上面的json -

import json
from pprint import pprint

with open('file.json') as data_file:    
    data = json.load(data_file)

print "Value1 - " , data["sentAt"].encode('utf-8')
print "Value2  - ", data["batch"][0]["URL"].encode('utf-8')
print "Value3 - ", data["batch"][0]["event"].encode('utf-8')

我能够通过value3打印value1。但我想知道是否有办法访问以下类型的json

{
   "sentAt":"2016-06-11T04:48:25Z",
   "Device":"iPhone6",
   "batch":[
      {
         "URL":"/laundry/Vanish",
         "event":"PageView",
         "createdAt":"2016-06-11T04:47:58Z"
      },
      {
         "listPrice":6.5,
         "product_id":47446,
         "category":"",
         "salePrice":5.2,
         "eventName":"ViewProduct",
         "prodName":"Vanish",
         "createdAt":"2016-06-11T04:47:59Z"
      }
   ]
}
{
   "sentAt":"2016-07-11T04:48:25Z",
   "Device":"iPhone5",
   "batch":[
      {
         "URL":"/laundry/NewProduct",
         "event":"NewPage",
         "createdAt":"2016-06-11T04:47:58Z"
      },
      {
         "listPrice":6.5,
         "product_id":47446,
         "category":"",
         "salePrice":5.2,
         "eventName":"ViewProduct",
         "prodName":"Vanish",
         "createdAt":"2016-06-11T04:47:59Z"
      },
   ]
}

正如您所看到的,上面的JSON有2个字典,我想访问第二个json字典中的数据。

例如 - 我想打印URL - / laundry / NewProduct而不是URL - / Laundry / Vanish

0 个答案:

没有答案