3

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
  • 2,759
  • 2
  • 32
  • 55

1 Answers1

7

Use getattr function:

getattr(x, foo)

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

heemayl
  • 35,775
  • 6
  • 62
  • 69