简体   繁体   中英

Parse Json if a certain value exists

I need to parse "order" from below JSON , if only value of "success" = 'true' , else raise an exception.

Tried below, but not sure how to include the 'true' check in try:

{  
   "success":true,
   "order":"123345"
} 

below is the code , I am trying , which is not giving any result from print as well.

import json
from pprint import pprint


data = json.load(open('data.json'))
#pprint(data)

try:
    check_key = data['success']
except KeyError:
    #continue
    print(check_key)
   #print(data['order'])

You should evaluate data['success'] in a condition, whether it is false, then you raise your exception.

import json

data = json.load(open('data.json'))

if data['success'] is not True:
  raise Exception("Success is false")

order = data['order']
print(order)

I need to parse "order" from below JSON , if only value of "success" = 'true' , else raise an exception.

There's no function that will automatically raise an exception if a value is False; you need to write that yourself.

But it's dead easy:

check_key = data.get('success')
if not check_key:
    raise MyKindOfError(f'response success was {check_key}')
do_stuff(data['order'])

(You don't actually need to use get there; you could let data['success'] raise a KeyError if it's not present, and then separately check the value for falsiness and raise your own error. But I assume you probably want to handle a missing success the same way as false , and the error you want to raise probably isn't KeyError , in which case this is simpler.)


As a side note, you've already parsed the JSON at this point . What you have is a dict .

The fact that it originally came from parsing JSON doesn't make any difference; it's a plain old Python dict , with all the same methods, etc., as any other dict . So, it really isn't helpful to think of "how do I … with JSON …"; that just misleads you into forgetting about how easy dict s are to use.

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