Python 2.7将Json循环输出保存到变量中?

时间:2018-04-24 03:44:29

标签: python python-2.7 variables printing output

目标: 我想将循环的输出保存到变量中,因此我可以使用输出发送电子邮件。

第一个问题:

JSON输出是一个重复的块,它可能是不一致的,所以我不确定该范围,所以我创建了一个for循环,它将满足我的需要。我知道它很乱。印刷语句标识我需要的一切;但是我需要将所有的print语句设置为一个变量或变量,这将给我更多的灵活性。

第二个问题:

如何结束循环?

Json数据看起来像;

{
"data": [
    {
        "attributes": {
            "name": "mike", 
            "color": "blue", 
            "size": "small", 
            "make": "mazda",
        "attributes": {
            "name": "John", 
            "color": "green", 
            "size": "big", 
            "make": "honda",



# Convert JSON Language to Script
jsonResponse=json.loads(json_object)

LOOP

a=0
for i in range(0,100):
     a = a + 1
     print ("Name:",(jsonResponse['data'][a]['attributes']['name']))
     print ("Color:",(jsonResponse['data'][a]['attributes']['Color']))
     print ("Size:",(jsonResponse['data'][a]['attributes']['Size']))
     print ("Make:",(jsonResponse['data'][a]['attributes']['Make']))
     print (" ")

EMAIL

# Email
from O365 import Message
myemail = x
password = y

o365_auth = ((myemail),(password))
m = Message(auth=o365_auth)
m.setRecipients(myemail)
m.setSubject('SUBJECT.')
m.setBody('print variable here')
m.sendMessage()

1 个答案:

答案 0 :(得分:0)

在您的示例中,'data'包含字典列表,因此您可以使用for a in dct['data']

循环显示这些字典

由于您想保存每个人的某些变量,我建议您只使用所需数据的词典列表:

dct = {'data': [{'attributes': {'name': 'mike', 'color': 'blue', 'size': 'small', 'make': 'mazda'}}, {'attributes': {'name': 'John', 'color': 'green', 'size': 'big', 'make': 'honda'}}]}

people = []
for a in dct['data']:
  people.append(a['attributes'])

print(people)

现在,您的属性数组中的每个人都有一个词典列表:

[{'name': 'mike', 'color': 'blue', 'size': 'small', 'make': 'mazda'},
{'name': 'John', 'color': 'green', 'size': 'big', 'make': 'honda'}]

您可以使用列表解析进一步简化:

people = [a['attributes'] for a in dct['data']]
相关问题