Parses a raw string input into a value compatible with a JSON schema. This does not perform a full JSON Schema validation. It only checks if the parsed **top-level type** matches the schema. If the parsed object does not match the schema and the schema accepts strings, the raw stri
(
raw_value: str,
schema: Dict[str, Any],
)
| 189 | |
| 190 | |
| 191 | def parse_value_for_schema( |
| 192 | raw_value: str, |
| 193 | schema: Dict[str, Any], |
| 194 | ) -> Any: |
| 195 | """Parses a raw string input into a value compatible with a JSON schema. |
| 196 | |
| 197 | This does not perform a full JSON Schema validation. It only checks if the |
| 198 | parsed **top-level type** matches the schema. |
| 199 | |
| 200 | If the parsed object does not match the schema and the schema accepts |
| 201 | strings, the raw string is returned. |
| 202 | |
| 203 | Args: |
| 204 | raw_value: The raw user input. |
| 205 | schema: JSON schema. |
| 206 | |
| 207 | Raises: |
| 208 | ValueError: If the input cannot be coerced to a value matching the |
| 209 | schema's top-level types. |
| 210 | |
| 211 | Returns: |
| 212 | The coerced value. |
| 213 | """ # noqa: DOC503 |
| 214 | parse_error: Optional[json.JSONDecodeError] = None |
| 215 | parsed: Any = None |
| 216 | try: |
| 217 | parsed = json.loads(raw_value) |
| 218 | except json.JSONDecodeError as e: |
| 219 | parse_error = e |
| 220 | |
| 221 | allowed = _schema_allowed_json_types(schema) |
| 222 | |
| 223 | if parse_error is None: |
| 224 | if not allowed: |
| 225 | return parsed |
| 226 | parsed_type = _json_type_of(parsed) |
| 227 | candidates = {parsed_type} if parsed_type else set() |
| 228 | # JSON Schema: integers are also valid numbers. |
| 229 | if parsed_type == "integer": |
| 230 | candidates.add("number") |
| 231 | if candidates & allowed: |
| 232 | return parsed |
| 233 | if "string" in allowed: |
| 234 | return raw_value |
| 235 | |
| 236 | raise ValueError( |
| 237 | f"Input does not match expected schema: got " |
| 238 | f"{parsed_type}, expected one of {sorted(allowed)}." |
| 239 | ) |
| 240 | |
| 241 | if "string" in allowed or not allowed: |
| 242 | return raw_value |
| 243 | |
| 244 | raise parse_error |
no test coverage detected