def serialize(struct, format, target=None, encoding='<STR_LIT:utf-8>'):
<EOL>if hasattr(target, '<STR_LIT>') and target.encoding:<EOL><INDENT>raise AnyMarkupError('<STR_LIT>')<EOL><DEDENT>fname = None<EOL>if hasattr(target, '<STR_LIT:name>'):<EOL><INDENT>fname = target.name<EOL><DEDENT>fmt = _get_format(format, fname)<EOL>try:<EOL><INDENT>serialized = _do_serialize(struct, fmt, encoding)<EOL>if target is None:<EOL><INDENT>return serialized<EOL><DEDENT>else:<EOL><INDENT>return target.write(serialized)<EOL><DEDENT><DEDENT>except Exception as e:<EOL><INDENT>raise AnyMarkupError(e, traceback.format_exc())<EOL><DEDENT>
Serialize given structure and return it as encoded string or write it to file-like object.

    Args:
        struct: structure (dict or list) with unicode members to serialize; note that list
            can only be serialized to json
        format: specify markup format to serialize structure as
        target: binary-opened file-like object to serialize to; if None (default),
            the result will be returned instead of writing to `target`
        encoding: encoding to use when serializing, defaults to utf-8
    Returns:
        bytestring with serialized structure if `target` is None; return value of
        `target.write` otherwise
    Raises:
        AnyMarkupError if a problem occurs while serializing