4

I created a namespace using json data as below, learnt from this SO answer

>>> from __future__ import print_function
>>> import json
>>> from types import SimpleNamespace as Namespace
>>> data = '{"name": "John Smith", "hometown": {"name": "New York", "id": 123}}'
>>> x = json.loads(data, object_hook=lambda d: Namespace(**d))
>>> x.name
'John Smith'

But if 'name' is to come from a variable, how can I access it?

>>> foo='name'
>>> x.foo
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'types.SimpleNamespace' object has no attribute 'foo'
>>> 
rodee
  • 3,233
  • 5
  • 34
  • 70

1 Answers1

8

Use getattr function:

getattr(x, foo)

would work as x.name when foo = 'name'.

heemayl
  • 39,294
  • 7
  • 70
  • 76