简体   繁体   English

json.dumps():如何用单个反斜杠转义双引号

[英]json.dumps() : how to escape double quotes with a single backslash

when I use json.dumps(), I get the following output:当我使用 json.dumps() 时,我得到以下 output:

>>> json.dumps("abc")
'"abc"'

This results in unescaped double quotes.这会导致未转义的双引号。 Is there a way to always have one backslash, something like:有没有办法总是有一个反斜杠,比如:

>>> json.dumps("abc", additional_param=?)
'\"abc\"'

Not sure if this is exactly what you want, but it might be:不确定这是否正是您想要的,但它可能是:

import json

print(json.dumps("abc").replace(r'\"', '"').replace('"', r'\"'))

Result:结果:

\"abc\"

It sounds like what you're asking for is double-encoded JSON.听起来您要的是双编码 JSON。

print(json.dumps(json.dumps("abc")))

...results in: ...结果是:

"\"abc\""

By contrast, single-encoding (without the REPL's implicit repr() ) looks like:相比之下,单编码(没有 REPL 的隐式repr() )看起来像:

print(json.dumps("abc"))

...and emits the correctly-encoded JSON document : ...并发出正确编码的 JSON 文档

"abc"

Note that this is correct JSON exactly as it is;请注意,这是正确的 JSON 原样; no backslashes are needed.不需要反斜杠。

No direct options are available for the json.dumps function. json.dumps function 没有直接选项可用。 You have to use some python tricks to do that.您必须使用一些 python 技巧来做到这一点。 Here is the prof, Docstring of json.dumps method.这是json.dumps方法的教授文档字符串。

def dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True,
        allow_nan=True, cls=None, indent=None, separators=None,
        default=None, sort_keys=False, **kw):
    """Serialize ``obj`` to a JSON formatted ``str``.

    If ``skipkeys`` is true then ``dict`` keys that are not basic types
    (``str``, ``int``, ``float``, ``bool``, ``None``) will be skipped
    instead of raising a ``TypeError``.

    If ``ensure_ascii`` is false, then the return value can contain non-ASCII
    characters if they appear in strings contained in ``obj``. Otherwise, all
    such characters are escaped in JSON strings.

    If ``check_circular`` is false, then the circular reference check
    for container types will be skipped and a circular reference will
    result in an ``OverflowError`` (or worse).

    If ``allow_nan`` is false, then it will be a ``ValueError`` to
    serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in
    strict compliance of the JSON specification, instead of using the
    JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).

    If ``indent`` is a non-negative integer, then JSON array elements and
    object members will be pretty-printed with that indent level. An indent
    level of 0 will only insert newlines. ``None`` is the most compact
    representation.

    If specified, ``separators`` should be an ``(item_separator, key_separator)``
    tuple.  The default is ``(', ', ': ')`` if *indent* is ``None`` and
    ``(',', ': ')`` otherwise.  To get the most compact JSON representation,
    you should specify ``(',', ':')`` to eliminate whitespace.

    ``default(obj)`` is a function that should return a serializable version
    of obj or raise TypeError. The default simply raises TypeError.

    If *sort_keys* is true (default: ``False``), then the output of
    dictionaries will be sorted by key.

    To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
    ``.default()`` method to serialize additional types), specify it with
    the ``cls`` kwarg; otherwise ``JSONEncoder`` is used.

    """

You can get the dcostring by help(json.dumps) or print(json.dumps.__doc__)您可以通过help(json.dumps)print(json.dumps.__doc__)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM