0

I'm new in python, I have a json with int as key values such as this:

"data": {
        "1": {
            "b": 1
} 
}

I want to cast it to object:

x = json.loads(json.dumps(data, indent=4, sort_keys=True), object_hook=lambda d: SimpleNamespace(**d))

now I want to access to b . how should I do that . this code returns error:

x.1.b

ali kamrani
  • 73
  • 1
  • 8

2 Answers2

0

In Python, variables are not allowed to start with a number.

getattr(x, "1").b

https://docs.python.org/3/library/functions.html#getattr

Related post: Can variable names in Python start with an integer?

Ryno_XLI
  • 161
  • 9
  • this error happens: TypeError: 'types.SimpleNamespace' object is not subscriptable – ali kamrani Nov 09 '21 at 03:55
  • 2
    I didn't see you were trying to convert it to `types.SimpleNamespace`. Variables are not allowed to start with a number. Although you can still access the attributes by doing: `getattr(x, "1")`. Although, I would recommend keeping the json as a dictionary object. – Ryno_XLI Nov 09 '21 at 04:06
0

I think it would be easier to use your dict directly.

data = {
    "1": {"b": 1} 
}

some_value = data["1"]["b"]

If you want to use SimpleNamespace you need to replace 1 with something like _1 to be able to use something like x._1.b because x.1.b raises a syntax error.

This can be done by recursively converting your dict to a SimpleNamespace object and inserting _ in all keys starting with a number.

def dict_to_namespace(d):
    return SimpleNamespace(
        **{
            (f"_{k}" if k[0].isdecimal() else k): (
                dict_to_namespace(v) if isinstance(v, dict) else v
            )
            for k, v in d.items()
        }
    )

x = dict_to_namespace(data)
some_value = x._1.b

Note: this will lead to errors if your dict/json keys contain special characters (spaces, dashes etc.)

d-k-bo
  • 513
  • 5
  • 12