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
Consider just tossing those values in a list, if you want to keep them separate from the json object:
Really though, do you need to put them in this separate list variable, when they are already easily accessible inside your json object
d
?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.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:
now
ids
is:converting json to object-like instance
If we have a nested dictionary like below or that one in the question
in python you should write this code:
but it is more fun to just write:
so the code that I wrote for converting a json to object, is here:
My code aimed to convert json to object but a dictionary in python could be more complex.