1

I would like to convert JSON nested array to Python nested list with one-liner Python method.

Below is the sample of my JSON nested array:

my_dict = {
    "background": "This is a test text.",
    "person": [
        {"name": "Max", "tranx_info": [
            {"tranx_date":"7/1/2020","amount": 82 },
            {"tranx_date":"27/2/2017","amount":177 }]
        },
        {"name": "Lily", "tranx_info": [
            {"tranx_date":"12/7/1989","amount": 165 },
            {"tranx_date":"28/2/1998","amount": 200 },
            {"tranx_date":"28/2/2098","amount": 34 }]
        }
    ]
}

I assume this will be nested list comprehension in Python? What I had tried so far but I'm only able to make the result into a list:

tranx_date_result = [x["tranx_date"] for y in my_dict["person"] for x in y["tranx_info"]]

#output
>>> ["7/1/2020","27/2/2017","12/7/1989","28/2/1998","28/2/2098"]

I would my "tranx_date" result to be in a nested list; something like this:

tranx_date_result = [["7/1/2020","27/2/2017"],["12/7/1989","28/2/1998","28/2/2098"]]

Any help is appreciated :)

1 Answer 1

2

Just use nested list comprehensions:

>>> [[x["tranx_date"] for x in y["tranx_info"]] for y in my_dict["person"]]
[['7/1/2020', '27/2/2017'], ['12/7/1989', '28/2/1998', '28/2/2098']]
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.