0

Having this json

[{'id': '16166cf3', 'quote': 'a.'}, {'id': '16166cfb', 'quote': 'b.'} ]

And this Class

class Quotes:
    def __init__(self, id, quote):
        self.id = id
        self.quote = quote

How can I transform the json arrayList into a list of Quotes??

For now I have this

with open("../json/quotes.json") as json_file:
            quote_list = json.load(json_file)
            print(quote_list)

Regards

1 Answer 1

0

Loop over the parsed list, and for each dict in the list, construct an instance of Quote with the fields from the dict. You can then append these instances to a new list.

with open("../json/quotes.json") as json_file:
    quote_list = json.load(json_file)
    print(quote_list)

instances = []

for q in quote_list:
    instances.append(Quotes(q["id"], q["quote"]))

More compact form using list comprehension, and assigning to the same variable:

with open("../json/quotes.json") as json_file:
    quote_list = json.load(json_file)
    print(quote_list)
    quote_list = [Quotes(q["id"], q["quote"]) for q in quote_list]
Sign up to request clarification or add additional context in comments.

1 Comment

thanks, there's nothing more functional to transform from A to B?

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.