0

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?

0

1 Answer 1

1
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',{})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.