简体   繁体   中英

Trouble parsing values out of json response with Python

I am running into a problem parsing out values from a JSON response.

The data coming back in the JSON in the response is:

{"account":{"id":"719fa9e0-a5de-4723-b693-c40cac85c4a4","name":"account_naughton9"}}

What I was trying to use to pull out the values for 'id' and 'name'

data = json.loads(post_create_account_response.text)    
account_assert_data = data.get('account_assert_data')
for account_data_parse in account_assert_data:
    account_id = account_data_parse['id']
    account_name = account_data_parse['name']

    print account_id
    print account_name

When I run this I get an error back stating:

    for account_data_parse in account_assert_data:
TypeError: 'NoneType' object is not iterable

My question is how do I pull out the id and name from this response so I can assert against those values in a unittest?

Your top-level JSON result has no such key, so data.get('account_assert_data') returned None .

There is a account key, but the value is not a list , it is a single dictionary. The following works:

account_assert_data = data.get('account')
if account_assert_data is not None:
    account_id = account_assert_data['id']
    account_name = account_assert_data['name']

Since it probably is an error if no account key is set, you could just presume the key exist and leave it to the unittesting framework to report the KeyError raised if it is missing as a test failure:

account_id = data['account']['id']
account_name = data['account']['name']

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