cdgriffith / Box

Python dictionaries with advanced dot notation access
https://github.com/cdgriffith/Box/wiki
MIT License
2.61k stars 106 forks source link

Dashes in keys #160

Closed kmatt closed 4 years ago

kmatt commented 4 years ago

Have a JSON data source with a nested key containing dashes.

Noting that makes for an invalid Python identifier, and "Box will automatically make otherwise inaccessible keys safe to access as an attribute", is there an option to support this format?

> j={'custom_fields': {'a_b_c':1, 'd-e-f':2 }}
> j
{'custom_fields': {'a_b_c': 1, 'd-e-f': 2}}

>b = Box(j)
>b.custom_fields.a_b_c
1

> b.custom_fields.d-e-f
---------------------------------------------------------------------------
BoxKeyError                               Traceback (most recent call last)
<ipython-input-247-dfed3a13203d> in <module>
----> 1 b.custom_fields.d-e-f

~/anaconda3/lib/python3.7/site-packages/box/box.py in __getattr__(self, item)
    484             if self._box_config["default_box"]:
    485                 return self.__get_default(item, attr=True)
--> 486             raise BoxKeyError(str(err)) from None
    487         return value
    488

BoxKeyError: "'Box' object has no attribute 'd'"
kmatt commented 4 years ago

Discovered after entering this ticket that b.custom_fields['d-e-f'] is an option, which may also be the answer to my issue.

cdgriffith commented 4 years ago

Hi @kmatt, that is one way, by default it will replace non usable characters, such as "-" with an underscore, so you could access it via b.custom_fields.d_e_f

Some details on how it works under the hood are in the wiki

kmatt commented 4 years ago

b.custom_fields.d_e_f

That works!