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")
| 134 | |
| 135 | |
| 136 | def 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 | try: |
| 160 | return Box.from_yaml(yaml_string=content) |
| 161 | except YAMLError: |
| 162 | raise BoxError("File is not YAML as expected") |
| 163 | except BoxError: |
| 164 | return BoxList.from_yaml(yaml_string=content) |
| 165 | elif string_type == "toon": |
| 166 | if not toon_available: |
| 167 | raise BoxError('toon is unavailable on this system, please install the "toon_format" package') |
| 168 | try: |
| 169 | return Box.from_toon(toon_string=content) |
| 170 | except (ToonDecodeError, ValueError): |
| 171 | raise BoxError("String is not TOON as expected") |
| 172 | except BoxError: |
| 173 | return BoxList.from_toon(toon_string=content) |
| 174 | else: |
| 175 | raise BoxError(f"Unsupported string_string of {string_type}") |