skip to Main Content

I have a json file (estate.json) that looks like this:

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "id": "724543e2-bd9d-4bef-b9d6-a3ae73d330b7",
      "properties": {
        "objektidentitet": "724543e2-bd9d-4bef-b9d6-a3ae73d330b7",
        "adressplatsattribut": {
          "adressplatstyp": "Gatuadressplats",
          "insamlingslage": "Infart"
        }
      }
    },
    {
      "type": "Feature",
      "id": "1209dd85-d454-46be-bf9c-f2472095fcdc",
      "properties": {
        "objektidentitet": "1209dd85-d454-46be-bf9c-f2472095fcdc",
        "adressplatsattribut": {
          "adressplatstyp": "Gatuadressplats",
          "insamlingslage": "Byggnad"
        }
      }
    },
    {
      "type": "Feature",
      "id": "e12ee844-c138-4f21-95cc-9254e78721d0",
      "properties": {
        "objektidentitet": "e12ee844-c138-4f21-95cc-9254e78721d0",
        "adressplatsattribut": {
          "adressplatstyp": "Gatuadressplats",
          "insamlingslage": "Infart"
        }
      }
    }
  ]
}

With the following lines:

f = open('estate.json')
d = json.load(f)

for id in d['features']:
    print(id['id'])

I can print the values from the keys ‘objektidentitet’ as:

724543e2-bd9d-4bef-b9d6-a3ae73d330b7
1209dd85-d454-46be-bf9c-f2472095fcdc
e12ee844-c138-4f21-95cc-9254e78721d0

I need to use these values in the upcoming step.
I believe that I need to create objects or variables for them?

I have tried creating classes (but I cant seem to understand them):

class obj(object):
    def __init__(self, d):
        for k, v in d.items():
            if isinstance(k, (list, tuple)):
                setattr(self, k, [obj(x) if isinstance(x, dict) else x for x in v])
            else:
                setattr(self, k, obj(v) if isinstance(v, dict) else v)

I have tried using recordclass and

def dict_to_class(class_name: Any, dictionary: dict) -> Any:
    instance = class_name()
    for key in dictionary.keys():
        setattr(instance, key, dictionary[key])
    return instance

3

Answers


  1. I need to use these values in the upcoming step. I believe that I
    need to create objects or variables for them? I have no idea where to
    start, I have been googling this for three months and nothing seem to
    match my dilemma?

    Consider just tossing those values in a list, if you want to keep them separate from the json object:

    d = json.loads('''{
      "type": "FeatureCollection",
      "features": [
        {
          "type": "Feature",
          "id": "724543e2-bd9d-4bef-b9d6-a3ae73d330b7",
          "properties": {
            "objektidentitet": "724543e2-bd9d-4bef-b9d6-a3ae73d330b7",
            "adressplatsattribut": {
              "adressplatstyp": "Gatuadressplats",
              "insamlingslage": "Infart"
            }
          }
        },
        {
          "type": "Feature",
          "id": "1209dd85-d454-46be-bf9c-f2472095fcdc",
          "properties": {
            "objektidentitet": "1209dd85-d454-46be-bf9c-f2472095fcdc",
            "adressplatsattribut": {
              "adressplatstyp": "Gatuadressplats",
              "insamlingslage": "Byggnad"
            }
          }
        },
        {
          "type": "Feature",
          "id": "e12ee844-c138-4f21-95cc-9254e78721d0",
          "properties": {
            "objektidentitet": "e12ee844-c138-4f21-95cc-9254e78721d0",
            "adressplatsattribut": {
              "adressplatstyp": "Gatuadressplats",
              "insamlingslage": "Infart"
            }
          }
        }
      ]
    }''')
    
    list_of_ids = [feature['id'] for feature in d['features']]
    print(list_of_ids)
    

    ['724543e2-bd9d-4bef-b9d6-a3ae73d330b7', '1209dd85-d454-46be-bf9c-f2472095fcdc', 'e12ee844-c138-4f21-95cc-9254e78721d0']
    

    Really though, do you need to put them in this separate list variable, when they are already easily accessible inside your json object d?

    Login or Signup to reply.
  2. If you wanted to use classes, that would look like this, but it is very unncessary for actually parsing JSON. A dictionary returned by json.load is already a Python object.

    class FeatureCollection:
      def __init__(self, features):
        self.features = features
    
    class Feature:
      def __init__(self, _id, properties):
        self._id = _id
        self.properties = properties
    
    features = []
    with open('estate.json') as f:
        d = json.load(f)
        for x in d['features']:
            features.append(Feature(x['id'], x['properties']))
    fc = FeatureCollection(features)
    
    Login or Signup to reply.
  3. You don’t need to convert json to object in this case but it is a satisfying way to work with jsons (and dictionary) like an object (like in javascript).

    in your case the answer is quite simple:

    d = json.loads("...")  # or json.load(open("path to json file"))
    ids = [i['id'] for i in d['features']]
    

    now ids is:

    ['724543e2-bd9d-4bef-b9d6-a3ae73d330b7', '1209dd85-d454-46be-bf9c-f2472095fcdc', 'e12ee844-c138-4f21-95cc-9254e78721d0']
    

    converting json to object-like instance

    If we have a nested dictionary like below or that one in the question

    {
      "a": "a simple string",
      "b": {
        "a": "nested string",
        "b": {
          "c": [
            [
              [1, 2, 3, 4, 5],
              [6, 7, 8, 9, 0]
            ],
            {"a": "test1", "b": "test2", "c": {"d": 1}},
          ]
        },
      },
    }
    

    in python you should write this code:

    d = json.load(...)
    d["b"]["b"]["c"][1]["c"]["d"] # -> 1
    

    but it is more fun to just write:

    d = jsonobj(json.load(...))
    d.b.b.c[1].c.d # -> 1
    

    so the code that I wrote for converting a json to object, is here:

    class jsonobj:
        def __init__(self, d):
            for k, v in d.items():
                self.__setattr__(k, jsonobj.nested_convert(v))
    
        @classmethod
        def nested_convert(cls, v):
            if isinstance(v, dict):
                return jsonobj(v)
            elif isinstance(v, list):
                return [jsonobj.nested_convert(i) for i in v]
            else:
                return v
    

    My code aimed to convert json to object but a dictionary in python could be more complex.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search