cdgriffith / Box

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

to_json() creates str #138

Closed staylorx closed 4 years ago

staylorx commented 4 years ago

Given a JSON example (Python 3.7.4 for all):

json_string = """
{  "entity": "ENTITY" }
"""
entity = Box.from_json(json_string)
print(entity)
print(type(entity))

I get,

{'entity': 'ENTITY'}
<class 'box.box.Box'>

Doing the same thing with YAML, given,

yaml_string = """
entity: "ENTITY"
"""

entity_temp = Box.from_yaml(yaml_string)
entity = entity_temp.to_json()
print(entity)
print(type(entity))

I get,

{"entity": "ENTITY"}
<class 'str'>

In the first example I can use the entity variable directly with requests.put(...,json=entity,...). The second one I have to json.loads()... which is pretty much why I was starting to use Box in the first place.

Your documentation is clear that to_json outputs as a string (or a filename).

Similar to json.load and json.loads, at some point maybe to_json() and to_jsons() might be useful?

Thanks for the useful work on this library. It's handy.

cdgriffith commented 4 years ago

I'm not sure I completely follow. In the second example you seem to be transforming the box to a JSON string unnecessarily? You could do the same thing as you did with the first example and use the box directly, if you are looking for a dict like object.

yaml_string = """
entity: "ENTITY"
"""

entity = Box.from_yaml(yaml_string)
print(entity)   # {'entity': 'ENTITY'}
print(type(entity)) # <class 'box.box.Box'>
cdgriffith commented 4 years ago

@staylorx were you able to figure it out?

staylorx commented 4 years ago

More or less. This can be closed. Thank you for looking into it.


From: Chris Griffith notifications@github.com Sent: Wednesday, March 11, 2020 8:12 AM To: cdgriffith/Box Cc: Steve Taylor; Mention Subject: Re: [cdgriffith/Box] to_json() creates str (#138)

@staylorx were you able to figure it out?

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub, or unsubscribe.

cdgriffith commented 4 years ago

Thanks for the reply. A little off topic, but one thing that you did make me think about is that to_json and the other converters can't take an open file handler like json.load can, and might be a nice addition.