In Python, unlike JavaScript etc., dictionary elements cannot be accessed by Attribute.
In other words, dict_obj ["value "]
is OK, but not dict_obj.value
.
The inconvenience this is when working with Json data. After all, on the JavaScript side, it can be accessed with Attribute, so it is human nature to want to write in the same way.
That's why I will show you how to access dict (assuming Json object this time) with Attribute.
In Python, loading Json makes it a dictionary.
>>> import json
>>> json.loads('{"v1":"xxxx", "v2":"vvvv"}')
{'v1': 'vvvv', 'v2': 'xxxx'}
As mentioned above, when accessing, it will be in the form of ʻobj ["v1"] and ʻobj.vi
will be NG.
The easiest way to solve this is to use a library called attrdict.
However, if you don't want to install it, you can use the following simple method.
When doing json.loads
, use ʻobject_hook to wrap each object in a class that implements attribute access (
getattr`). You can now access the element via Attribute.
import json
class AttributeDict(object):
def __init__(self, obj):
self.obj = obj
def __getstate__(self):
return self.obj.items()
def __setstate__(self, items):
if not hasattr(self, 'obj'):
self.obj = {}
for key, val in items:
self.obj[key] = val
def __getattr__(self, name):
if name in self.obj:
return self.obj.get(name)
else:
return None
def fields(self):
return self.obj
def keys(self):
return self.obj.keys()
if __name__ == "__main__":
attribute_json = json.loads('{"v1":"xxxx", "v2":"vvvv"}', object_hook=AttributeDict)
print("attribute_json.v1 = {0}".format(attribute_json.v1))
json_with_array = json.loads('{"arr":[{"v":"xxxx"}, {"v":"vvvv"}]}', object_hook=AttributeDict)
print("json_with_array[0].v = {0}".format(json_with_array.arr[0].v))
Execution result
attribute_json.v1 = xxxx
json_with_array[0].v = xxxx
If you can access Attribute, you will be able to complete the code, so it will be easier to implement. I tried it.
attrdict using JSON keys as python attributes in nested JSON soundcloud-python/resource.py Sample on Gist
Recommended Posts