python - 将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']]
解决方案
我认为你误解了语法。是在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']]
推荐阅读
- android - Android 应用程序用户卸载详情
- php - 有没有办法在 WordPress 的 .twig 文件中编写 PHP 代码?我正在尝试使用 .twig 模板文件中的表单值发送邮件
- javascript - 将 Google Maps API 与 Firebase 结合使用
- javascript - Discord Bot公告频道
- python - 如何在 Dash 中将条形图旋转 180 度?
- python-2.7 - 打印变量时延迟出现未处理的错误
- php - Netsuite 项目履行无效的行项目
- java - 使用 newSingleThreadExecutor 消除 ExecutorService 中的竞争条件
- python - Python:具有多个元素的数组的真值是模棱两可的。使用 a.any() 或 a.all()
- node.js - 使用 Node.JS 使用 Apple 的 .p8 文件签署 JWT