Skip to content
Advertisement

Parsing JSON array into class instance objects?

I’m trying to parse some data in Python I have some JSON:

JavaScript

If I wanted to parse the "metros" array into and array of Python class Metro objects, how would I setup the class?

I was thinking:

JavaScript

So I want to go through each metro and put the data into a corresponding Metro object and place that object into a Python array of objects…How can I loop through the JSON metros?

Advertisement

Answer

If you always get the same keys, you can use ** to easily construct your instances. Making the Metro a namedtuple will simplify your life if you are using it simply to hold values:

JavaScript

then simply

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement