Box icon indicating copy to clipboard operation
Box copied to clipboard

REQ: Create equivalent to box.from_file for strings (box.from_str ?)

Open richieadler opened this issue 4 years ago • 4 comments

Sometimes it's not known beforehand if the value of a string will contain a list or a dict.

It would be useful to have a function to autodetect the required type (Box or BoxList) as it is done for box.from_file.

Alternatively, enhance box.from_file to accept a file-like (but in that case if you have a str, you have to resort to io.StringIO; a separate function, possible called box.from_str, would be preferable).

richieadler avatar Apr 01 '21 03:04 richieadler

The main issue with this is that from_file relies on the extension to know what transform it uses, it doesn't blindly guess.

from_str would require just running everything on it and seeing what works, which can be handy but wrong. I personally don't like the unpredictability of it

cdgriffith avatar Nov 10 '21 22:11 cdgriffith

from_str would require just running everything on it and seeing what works, which can be handy but wrong. I personally don't like the unpredictability of it

How about this: determine the format from a mandatory parameter, but detect whether is a BoxList or a Box from the content? That was my main goal anyway.

mhuerta-endava avatar Nov 10 '21 22:11 mhuerta-endava

Thinking about it a bit more, I think it would be safe to assume json standard (as that is the only converter in standard library), and have a parameter for changing type.

def box_from_string(content: str, string_type: str = "json") -> Union[Box, BoxList]:
    """
    Parse the provided string into a Box or BoxList object as appropriate.

    :param content: String to parse
    :param string_type: manually specify file type: json, toml or yaml
    :return: Box or BoxList
    """

Thoughs?

cdgriffith avatar Nov 11 '21 16:11 cdgriffith

Thoughs?

Seems reasonable. (Sorry for the account confusion, it's the same person)

richieadler avatar Nov 11 '21 18:11 richieadler

Added in 6.10.0 https://github.com/cdgriffith/Box/releases/tag/6.10.0

cdgriffith avatar Oct 30 '22 02:10 cdgriffith