0

I have a json file containing NZ regions and towns:

{
    "region": [
        {
            "region_name": "northland",
            "towns": [
                "whangarei",
                "paihia",
                "russel"
            ]
        },
        {
            "region_name": "auckland",
            "towns": [
                "auckland",
                "porirua"
            ]
        }
    ]
}

I have also defined a a Region class to deserialize this file:

class Region:
    def __init__(self):
        self.region_name = ''
        self.towns = []

I want to convert the above json file to an array of Region, this is what I have tried:

import json

def get_nz_regions():
    with open('location/nz_regions.json') as json_file:
        nz_regions = json.load(json_file)

        # return an array of Region

1 Answer 1

1

Are you looking for something like

d = {
    "region": [
        {
            "region_name": "northland",
            "towns": [
                "whangarei",
                "paihia",
                "russel"
            ]
        },
        {
            "region_name": "auckland",
            "towns": [
                "auckland",
                "porirua"
            ]
        }
    ]
}

class Region:
    def __init__(self, region_name, towns):
        self.region_name = region_name
        self.towns = towns
        
d_deserialized = {"region":[]}
for each_region in d["region"]:
    d_deserialized["region"].append(Region(each_region["region_name"], each_region["towns"]))
    
print(d_deserialized)
{'region': [<__main__.Region object at 0x0000022344DB3DF0>, <__main__.Region object at 0x0000022344DB3D30>]}
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.