Parsing Helpers

This is a collection of functions used to convert untyped param strings into their appropriate JSON schema types.

doctor.parsers._parse_array(value)[source]

Coerce value into an list.

Parameters:value (str) – Value to parse.
Returns:list or None if the value is not a JSON array
Raises:TypeError or ValueError if value appears to be an array but can’t be parsed as JSON.
doctor.parsers._parse_boolean(value)[source]

Coerce value into an bool.

Parameters:value (str) – Value to parse.
Returns:bool or None if the value is not a boolean string.
doctor.parsers._parse_object(value)[source]

Coerce value into a dict.

Parameters:value (str) – Value to parse.
Returns:dict or None if the value is not a JSON object
Raises:TypeError or ValueError if value appears to be an object but can’t be parsed as JSON.
doctor.parsers._parse_string(value)[source]

Coerce value into a string.

This is usually a no-op, but if value is a unicode string, it will be encoded as UTF-8 before returning.

Parameters:value (str) – Value to parse.
Returns:str
doctor.parsers.parse_json(value)[source]

Parse a value as JSON.

This is just a wrapper around json.loads which re-raises any errors as a ParseError instead.

Parameters:value (str) – JSON string.
Returns:the parsed JSON value
doctor.parsers.parse_value(value, allowed_types, name='value')[source]

Parse a value into one of a number of types.

This function is used to coerce untyped HTTP parameter strings into an appropriate type. It tries to coerce the value into each of the allowed types, and uses the first that evaluates properly.

Because this is coercing a string into multiple, potentially ambiguous, types, it tests things in the order of least ambiguous to most ambiguous:

  • The “null” type is checked first. If allowed, and the value is blank (“”), None will be returned.
  • The “boolean” type is checked next. Values of “true” (case insensitive) are True, and values of “false” are False.
  • Numeric types are checked next – first “integer”, then “number”.
  • The “array” type is checked next. A value is only considered a valid array if it begins with a “[” and can be parsed as JSON.
  • The “object” type is checked next. A value is only considered a valid object if it begins with a “{” and can be parsed as JSON.
  • The “string” type is checked last, since any value is a valid string. Unicode strings are encoded as UTF-8.
Parameters:
  • value (str) – Parameter value. Example: “1”
  • allowed_types (list) – Types that should be attempted. Example: [“integer”, “null”]
  • name (str) – Parameter name. If not specified, “value” is used. Example: “campaign_id”
Returns:

a tuple of a type string and coerced value

Raises:

ParseError if the value cannot be coerced to any of the types