所以我一直在研究Json和一些比较。在
所以基本上我有一个Json,其中一些元素包含在一些元素中,而有些元素没有
我遇到的问题是,脚本一遍又一遍地继续脚本,但是由于异常而从不执行任何操作,比如找不到元素etcPrice,estimatedLaunchDate,这些元素将在Json中找到
sample = {
"threads": [{
"seoTitle": "used food",
"other_crap": "yeet"
},
{
"seoTitle": "trucks",
"other_crap": "it's a fox!"
"product": {
"imageUrl": "https://imagerandom.jpg",
"price": {
"fullRetailPrice": 412.95
},
"estimatedLaunchDate": "2018-06-02T03:00:00.000",
"publishType ": "DRAW"
},
{
"seoTitle": "rockets",
"other_crap": "i'm rocket man"
},
{
"seoTitle": "helicopter",
"other_crap": "for 007"
"product": {
"imageUrl": "https://imagerandom.jpg",
"price": {
"fullRetailPrice": 109.95
},
"estimatedLaunchDate": "2018-06-19T00:00:00.000",
"publishType": "FLOW"
}
}
]
}
正如您所看到的,在某些json元素中有一些额外的信息,而我遇到了一个问题,我该如何使它继续或只是添加etc“Price not found”,“publishType not found”,然后继续其余的json?在
到目前为止,我已经做了一个代码:
^{pr2}$如您所见,try except方法中有4个打印,如果其中一个(fullRetailPrice、estimatedLaunchDate、publishType)将抛出异常,并且不会继续执行其余代码,这意味着它将在"seoTitle": "trucks",
元素之后消亡!在
我不会重写整个示例,但是假设在查找值时
你所遵循的一个或多个键可能不在那里。你可以通过
^{pr2}$get
的第二个参数是在找不到所需键时返回的值。使此返回为空字典{}
将使您可以一直检查该行直到结束。如果没有找到任何键,最后一个get
将返回None
。然后,您可以检查foo
是否为None,并适当地打印一条错误消息。在相关问题 更多 >
编程相关推荐