6

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'
>>> 
2
  • 1
    If you want to look the values up by name like this, why aren't you just using a dict (the default) instead of a SimpleNamespace? Commented Aug 2, 2018 at 18:04
  • @abarnet, yes, I will do so, thanks. Commented Aug 2, 2018 at 19:08

1 Answer 1

10

Use getattr function:

getattr(x, foo)

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.