2016-06-23 67 views
0

我想從JSON文件中抓取數據。我能夠從一些標籤中抓取數據,但很少有嵌套標籤給出問題。以下是該文件的樣本 -刮JSON數組嵌套標記

{"orders":[{ 
    "order_id":9000, 
    "flight_start":"2017-06-15T05:00:00.000Z", 
    "flight_end":"2017-06-22T05:00:00.000Z", 
    "spots":[{ 
     "spot_id":7354259, 
     "spot_length":15}], 
    "constraints":{ 
     "forbid":[{ 
     "network":"BRVO"}, 
     {"network":"DSE"}, 
     {"network":"ESPN"}, 
     {"network":"DFC"}, 
     {"hours":[2,6], 
     "days_of_week":["Monday","Tuesday","Thursday","Friday"]}, 
     {"hours":[2,6], 
     "days_of_week":["Saturday","Sunday"]}], 
     "allocation":[{ 
     "hours":[6,9], 
     "impressions":{ 
      "min":0.05, 
      "max":0.05}, 
     "days_of_week":["Monday","Tuesday","Wednesday","Thursday","Friday"]},{ 
     "hours":[20,0], 
     "impressions":{"min":0.5,"max":0.5}, 
     "days_of_week":["Monday","Tuesday","Wednesday","Thursday","Friday"]},{ 
     "budget":{ 
      "min":1, 
      "max":1}, 
     "spot_length":15}]}}]} 

我無法從網絡標籤刮掉所有的值,它只是從所有網絡選項卡每個順序返回頂部值。

我使用下面的代碼 -

import urllib 
import json 
url = 'http://vw-test.elasticbeanstalk.com/test' 
json_obj = urllib.request.urlopen(url).read().decode('UTF-8') 
data = json.loads(json_obj) 
for i in data["orders"]: 
    k = i["order_id"] 
    j = i["flight_start"] 
    l = i["flight_end"] 
    m = i ['spots'] 
    for value in m:  
     a = value["spot_length"] 
     b = value["spot_id"] 
    n = i["constraints"] 
    c = n["forbid"] 
    d = c[0] 
    e = d["network"] 
    print(e) 

如果任何人能幫助我想出解決辦法,我會非常感激。

回答

1

你問題中的json數據不完整。做一些假設,這可能會發揮作用:

for i in data["orders"]: 
    k = i["order_id"] 
    j = i["flight_start"] 
    l = i["flight_end"] 
    m = i ['spots'] 
    for value in m: 
     a = value["spot_length"] 
     b = value["spot_id"] 
    n = i["constraints"] 
    c = n["forbid"] 
    d = c[0] 
    networks = [d["network"] for d in c if "network" in d] 
    print(networks) 
+0

是的,這工作,非常感謝。順便說一句,如果你想看看,代碼中給出了json文件的鏈接。 – Uasthana

+0

不客氣。我的意思是說,在你的問題中顯示的樣本數據需要以''spot_length'結尾:15}]}}]}'結構良好。 – martineau

+0

是的,你是對的對不起,我已經修復它的問題。非常感謝 – Uasthana