MCPcopy Create free account
hub / github.com/cdgriffith/Box / box_from_string

Function box_from_string

box/from_file.py:136–177  ·  view source on GitHub ↗

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

(content: str, string_type: str = "json")

Source from the content-addressed store, hash-verified

134
135
136def box_from_string(content: str, string_type: str = "json") -> Box | BoxList:
137 """
138 Parse the provided string into a Box or BoxList object as appropriate.
139
140 :param content: String to parse
141 :param string_type: manually specify file type: json, toml or yaml
142 :return: Box or BoxList
143 """
144
145 if string_type == "json":
146 try:
147 return Box.from_json(json_string=content)
148 except JSONDecodeError:
149 raise BoxError("File is not JSON as expected")
150 except BoxError:
151 return BoxList.from_json(json_string=content)
152 elif string_type == "toml":
153 try:
154 return Box.from_toml(toml_string=content)
155 except toml_decode_error: # type: ignore
156 raise BoxError("File is not TOML as expected")
157 # A TOML document is always a table, so unlike the other formats it is never a BoxList
158 elif string_type == "yaml":
159 if not yaml_available:
160 raise BoxError('yaml is unavailable on this system, please install the "ruamel.yaml" or "PyYAML" package')
161 try:
162 return Box.from_yaml(yaml_string=content)
163 except YAMLError:
164 raise BoxError("File is not YAML as expected")
165 except BoxError:
166 return BoxList.from_yaml(yaml_string=content)
167 elif string_type == "toon":
168 if not toon_available:
169 raise BoxError('toon is unavailable on this system, please install the "toon_format" package')
170 try:
171 return Box.from_toon(toon_string=content)
172 except (ToonDecodeError, ValueError):
173 raise BoxError("String is not TOON as expected")
174 except BoxError:
175 return BoxList.from_toon(toon_string=content)
176 else:
177 raise BoxError(f"Unsupported string_string of {string_type}")

Calls 5

BoxErrorClass · 0.90
from_jsonMethod · 0.45
from_tomlMethod · 0.45
from_yamlMethod · 0.45
from_toonMethod · 0.45