2015-05-09 45 views
1

我已經成功地編寫了一個腳本來從json文件中提取信息,並以一種我可以使用的方式解析它,但我此刻必須手動打印每個字符串。我想循環這個如果可能但堅持從哪裏開始?python循環與JSON,而不是手動打印出每場比賽

的Python

from __future__ import print_function 
import json 
import sys 
from pprint import pprint 

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

#json_file.close() 

# Print all json data 
#pprint(data) 
#screen_list = data['screen'] 
print ("Screens availble",len (data['screen'])) 

#pprint(data["screen"][1]["id"]) 
#pprint(data["screen"][1]["user"]) 
#pprint(data["screen"][1]["password"]) 
#pprint(data["screen"][1]["code"]) 


#How to loop this 

print ("https://",data["screen"][0]["server"],"/test/test.php?=",data["screen"][0]["code"],sep='') 
print ("https://",data["screen"][1]["server"],"/test/test.php?=",data["screen"][1]["code"],sep='') 
print ("https://",data["screen"][2]["server"],"/test/test.php?=",data["screen"][2]["code"],sep='') 

JSON

{ 
    "screen": [ 
     { 
      "id": "1", 
      "user": "[email protected]", 
     "password": "letmein", 
     "code": "123456", 
     "server": "example.com" 
     }, 
     { 
      "id": "2", 
      "user": "[email protected]", 
     "password": "letmein", 
     "code": "123455", 
     "server": "example.com" 
     }, 
     { 
      "id": "3", 
      "user": "[email protected]", 
     "password": "letmein", 
     "code": "223456", 
     "server": "example.com" 
     } 
    ] 
} 

回答

0

您可以通過類型的字典列表迭代:

for d in data["screen"]: 
    print ("https://",d["server"],"/test/test.php?=",d["code"],sep='') 

日期:

https://example.com/test/test.php?=123456 
https://example.com/test/test.php?=123455 
https://example.com/test/test.php?=223456 
+0

這一個完美的作品 – Grimlockz

+0

@Grimlockz,沒有後顧之憂,很高興它幫助。 –

1

您已將data['screen']拉出到名爲screen_list的變量中。該變量爲list,因此您可以使用它與其他任何列表相同 - 請致電len,爲其編制索引或循環播放。所以:

screen_list = data['screen'] 
print("Screens availble", len(screen_list)) 

for screen in screen_list: 
    pprint(screen['id']) 
    pprint(screen['user']) 
    pprint(screen['password']) 
    pprint(screen['code']) 

而且,向下跌破,只需再次循環:

for screen in screen_list: 
    print("https://", screen["server"], "/test/test.php?=", screen["code"], sep='') 

(我假設你要打印出所有的屏幕信息,然後打印出所有的網址,如果你。想在您打印信息,同時打印的每個網址,只需將它們合併成一個圈。)


作爲一個方面說明,這是瞭解字符串格式化的好時機。如果您想要使用這些URL,例如將它們傳遞給urllib2requests,則不能將它們打印出來,而必須將它們製作成字符串。即使你只是想打印出來,格式化通常更容易閱讀,更難以出錯。所以:

print("https://{}/test/test.php?={}".format(screen["server"], screen["code"])) 

......或者......

print("https://{server}/test/test.php?={code}".format(**screen)) 
+0

謝謝,我將使用這個URL與硒打開它們 - 我試圖使用你的兩個打印命令,但我得到IndentationError:預計一個縮進塊 – Grimlockz

+0

@Grimlockz:你知道縮進在Python中的工作原理嗎? – abarnert

+0

剛剛學習python,所以需要選擇該命令來縮進它 – Grimlockz