首页 > 解决方案 > 将json数据保存到python列表时出现问题

问题描述

我当时正试图从我的 json 数据中获取两个属性,并将它们作为一个项目添加到我的 python 列表中。但是,当尝试添加这两个时:['emailTypeDesc']['createdDate'] 它会引发错误。有人可以帮忙吗?提前致谢!

json:

{
'readOnly': False,
'senderDetails': {'firstName': 'John', 'lastName': 'Doe', 'emailAddress': 'johndoe@gmail.com', 'emailAddressId': 123456, 'personalId': 123, 'companyName': 'ACME‘},
'clientDetails': {'firstName': 'Jane', 'lastName': 'Doe', 'emailAddress': 'janedoe@gmail.com', 'emailAddressId': 654321, 'personalId': 456, 'companyName': 'Lorem Ipsum‘}},
'notesSection': {},
'emailList': [{'requestId': 12345667, 'emailId': 9876543211, 'emailType': 3, 'emailTypeDesc': 'Email-In', 'emailTitle': 'SampleTitle 1', 'createdDate': '15-May-2020 11:15:52', 'fromMailList': [{'firstName': 'Jane', 'lastName': 'Doe', 'emailAddress': 'janedoe@gmail.com',}]},
          {'requestId': 12345667, 'emailId': 14567775, 'emailType': 3, 'emailTypeDesc': 'Email-Out', 'emailTitle': 'SampleTitle 2', 'createdDate': '16-May-2020 16:15:52', 'fromMailList': [{'firstName': 'Jane', 'lastName': 'Doe', 'emailAddress': 'janedoe@gmail.com',}]},
          {'requestId': 12345667, 'emailId': 12345, 'emailType': 3, 'emailTypeDesc': 'Email-In', 'emailTitle': 'SampleTitle 3', 'createdDate': '17-May-2020 20:15:52', 'fromMailList': [{'firstName': 'Jane', 'lastName': 'Doe', 'emailAddress': 'janedoe@gmail.com',}]   
}

Python:

final_list = []

data = json.loads(r.text)
myId = [(data['emailList'][0]['requestId'])]
for each_req in myId:
    final_list.append(each_req)
myEmailList = [mails['emailTypeDesc']['createdDate'] for mails in data['emailList']]
for each_requ in myEmailList:
    final_list.append(each_requ)
return final_list

当我运行上面的代码时出现这个错误:

TypeError: string indices must be integers

所需的输出final_list

[12345667, 'Email-In', '15-May-2020 11:15:52',  'Email-Out', '16-May-2020 16:15:52', 'Email-In', '17-May-2020 20:15:52']

我的问题肯定在这一行:

myEmailList = [mails['emailTypeDesc']['createdDate'] for mails in data['emailList']]

因为当我在没有第二个属性的情况下运行它时['createdDate']它会起作用,但我需要两个属性final_list

  myEmailList = [mails['emailTypeDesc'] for mails in data['emailList']]

标签: pythonjson

解决方案


我认为你误解了语法。是在object里面mails['emailTypeDesc']['createdDate']找key ,其实它们是同级的两个item。'createdDate' mails['emailTypeDesc']

由于mails['emailTypeDesc']是字符串,而不是字典,因此您会得到引用的错误。您似乎想将这两个项目添加mails['emailTypeDesc']mails['createdDate']您的列表中。我不确定您是否愿意将这些组合成一个字符串或创建一个子列表或其他东西。这是一个子列表选项。

myEmailList = [[mails['emailTypeDesc'], mails['createdDate']] for mails in data['emailList']]

推荐阅读