首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Python -如果找不到json元素,如何继续

Python -如果找不到json元素,如何继续
EN

Stack Overflow用户
提问于 2018-06-28 07:06:43
回答 1查看 1.4K关注 0票数 1

所以我一直在尝试Json和一些比较。

所以基本上我有一个Json,其中一些元素包含在一些元素中,而另一些则不包含。

我遇到的问题是,脚本一遍又一遍地继续执行脚本,但由于无法找到将在此Json中找到的元素etc Price,estimatedLaunchDate,因此永远不会执行任何操作

代码语言:javascript
复制
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的其余部分?

到目前为止,我已经编写了一段代码来实现这一点:

代码语言:javascript
复制
old_list = []

    while True:
        try:
            resp = requests.get("www.helloworld.com")
            new_list = resp.json()['threads']

            for item in new_list:

                newitemword = item['seoTitle']

                if newitemword not in old_list:
                    try:

                        print(newitemword) #item name

                        print(str(item['product']['price']['fullRetailPrice']))
                        print(item['product']['estimatedLaunchDate']) 
                        print(item['product']['publishType']) 


                        old_list.append(newitemword)



                    except Exception as e:
                        print(e)
                        print("ERROR")
                        time.sleep(5)
                        continue


            else:
                randomtime = random.randint(40, 60)
                time.sleep(randomtime)

正如您所看到的,在try except方法中有4个打印,如果其中一个(fullRetailPrice,estimatedLaunchDate,publishType),它将抛出异常,并且不会继续其余的代码,这意味着它将在"seoTitle": "trucks",元素之后死亡!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-28 07:21:40

我不会重写整个示例,但是假设当您查找值时

代码语言:javascript
复制
print(str(item['product']['price']['fullRetailPrice']))

您遵循的一个或多个键可能不在那里。您可以通过执行以下操作在代码中检测到这一点

代码语言:javascript
复制
foo = item.get('product', {}).get('price', {}).get('fullRetailPrice')
if foo:
    print(str(foo))
else:
    print('Retail price could not be found')

get的第二个参数是在找不到所需键时返回的值。将此返回设置为空字典{}将允许您一直检查该行,直到最后。如果找不到任何键,最后一个get将返回None。然后,您可以检查foo是否为None,并相应地打印错误消息。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51072596

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档