简体   繁体   中英

How to check JSON string for list using Python?

I'm reading strings from a file that are in JSON format, all of which could be slightly different. Specifically the following examples:

No List Example

[{"pricing-model":{"qualifier":{"and":{"all":{"equals":{"constant":...

List Example

{"pricing-model":{"qualifier":{"or":{"and":[{"all":{"equals":{"constant":...

If the string contains a list, I need to process it differently than if does not have a list.

Example Code

with open('my.jason') as f:
    data = json.load(f)
    for item in data:
        item = [item]
        # Get dictionary items
        item.get('pricing-model',{}).get('qualifier',{}).get('and',{}).get('all',{})\
                                    .get('equals',{}).get('constant',{})

        # Get list items
        item.get('pricing-model',{}).get('qualifier',{}).get('and',[])

But how do I validate if the sting contains a list so I can run the correct.get?

if isinstance(item['pricing-model']['qualifier']['and'], list):
    # Get list items
    item.get('pricing-model',{}).get('qualifier',{}).get('and',[])
else:
    item.get('pricing-model',{}).get('qualifier',{}).get('and',{}).get('all',{})\
                                    .get('equals',{}).get('constant',{})

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