简体   繁体   中英

how to handle Json Keyerror in Python

I have many elements as json Data like this:

{
   "listing_1":{
      "general_info":{
         "bedrooms":{
            "value":5
         },
         "bathrooms":{
            "value":4,
         "parking":{
            "value":3
         }
      }
   }
}

the problem is the key "general_info" in some elements is missing. i have tried to implement get() but with no success:

beds_number = data["listing_1"].get("general_info", 0)["bedrooms"]["value"]

to summurize if the key is missing i want assign to "beds_number" to "None".

l think that you cannot do it in one line. Try something like this:

beds_number = data["listing_1"]
if "general_info" in beds_number :
    beds_number = beds_number["general_info"]["bedrooms"]["value"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM