0

I have a json and I'd like to get only specific values into a list. I can do this just fine iterating through, but I'm wondering if there's an easy one-liner list comprehension method to do this. Suppose I have a json:

{
    "results": {
        "types": 
        [
            {
                "ID": 1
                "field": [
                    {
                        "type": "date",
                        "field": "PrjDate"
                    },
                    {
                        "type": "date",
                        "field": "ComplDate"
                    }
                ]
            }
        ]
    }
}

I'd like to get all of the field values into a single list:

fieldsList = ['PrjDate', 'ComplDate']

I can do this easily with

for types in myjson['results']['types']:
    fieldsList = []
    for fields in types['field']:
        fieldsList.append(fields['field'])

But that seems unnecessarily clunky, is there an easy one-liner list comprehension method I can use here?

2
  • Can you have more than one element in types: [...]? Commented Feb 13, 2019 at 17:38
  • @marekful yes there will usually be more than one element in there. See edit, there was an ID field I forgot to include. Commented Feb 13, 2019 at 17:38

1 Answer 1

2

You could try

myfields = [fields['field'] for types in myjson['results']['types'] for fields in types['field']]
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.