Skip to content

dumps() crashes with TypeError when a list contains non-string values (e.g. integers) #16

Description

@anthonyoteri

Bug

dumps() raises TypeError: argument of type 'int' is not a container or iterable when serializing a list that contains non-string scalar values such as integers or floats.

Root cause

In _dump, when iterating list items, non-dict items are passed directly to _escape():

yield '%s%s\n' % (' ' * (indent + 2), _escape(subvalue))

_escape() does for ch in _ESCAPE_CHARACTERS: if ch in k — which fails when k is an int (or any non-string type) because in on a string requires the left operand to also be a string.

Reproducer

import structprop
structprop.dumps({"ids": [1, 2, 3]})
# TypeError: argument of type 'int' is not a container or iterable

Fix

_escape should coerce its argument to str before testing membership, or _dump should coerce non-string list items to strings before passing them to _escape:

def _escape(k):
    k = str(k)
    for ch in _ESCAPE_CHARACTERS:
        if ch in k:
            return '"%s"' % (k,)
    return k

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions