python使用JSON循环,而不是手动打印每个匹配项

python使用JSON循环,而不是手动打印每个匹配项,python,json,loops,Python,Json,Loops,我已经成功地编写了一个脚本,从json文件中提取信息,并以我可以使用的方式对其进行解析,但目前我必须手动打印每个字符串。如果可能的话,我想循环这个问题,但我还是坚持从哪里开始 蟒蛇 from __future__ import print_function import json import sys from pprint import pprint with open('screen.json') as data_file: data = json.load(data_fi

我已经成功地编写了一个脚本,从json文件中提取信息,并以我可以使用的方式对其进行解析,但目前我必须手动打印每个字符串。如果可能的话,我想循环这个问题,但我还是坚持从哪里开始

蟒蛇

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


您可以在DICT列表上进行迭代:

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


您已经将
数据['screen']
拉出到名为
screen\u 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。如果您要在打印信息的同时打印每个URL,只需将它们合并到一个循环中即可。)


作为旁注,现在是学习字符串格式的好时机。如果您想使用这些URL,例如,将它们传递到
urllib2
请求
,您不能只打印出来,必须将它们转换成字符串。即使您只是想打印出来,格式通常更容易阅读,也更难出错。因此:

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

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

谢谢,我将使用此URL与selenium一起打开它们-我已尝试使用您的两个打印命令,但我得到IndentationError:预期为缩进block@Grimlockz:您了解缩进在Python中是如何工作的吗?目前正在学习Python,因此需要将该命令标记为缩进it@Grimlockz:是的,如果你想在循环中发生什么事情,你必须比
for
语句缩进一步,就像我回答前半部分的例子一样。@Grimlockz,不用担心,很高兴它有帮助。
print("https://{}/test/test.php?={}".format(screen["server"], screen["code"]))
print("https://{server}/test/test.php?={code}".format(**screen))