python把字典转化为json的时候出现的编码问题

python虽好用,编码愁死人

做一个服务,需要把数据以json的形式发送出去,服务端写的时候是先把数据保存到字典里,然后通过json的dumps()转化为json ,这里就需注意dumps的具体用法,如下例子所示:

import json
json.dumps("中国")

在这里插入图片描述
这里输出的是汉字的ascii码,想要输出汉字就需要把参数设置好ensure_ascii=False

json.dumps('中国',ensure_ascii=False)

在这里插入图片描述
接下来我们来看一下源码把

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.

    """
    # cached encoder
    if (not skipkeys and ensure_ascii and
        check_circular and allow_nan and
        cls is None and indent is None and separators is None and
        default is None and not sort_keys and not kw):
        return _default_encoder.encode(obj)
    if cls is None:
        cls = JSONEncoder
    return cls(
        skipkeys=skipkeys, ensure_ascii=ensure_ascii,
        check_circular=check_circular, allow_nan=allow_nan, indent=indent,
        separators=separators, default=default, sort_keys=sort_keys,
        **kw).encode(obj)

函数中有如下的说明,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.

如果是false的话就会返回给JSONEncoder以进行 编码,以返回非ascii码

        if isinstance(o, str):
            if self.ensure_ascii:
                return encode_basestring_ascii(o)
            else:
                return encode_basestring(o)
def encode_basestring(string): # real signature unknown; restored from __doc__
    """
    encode_basestring(string) -> string
    
    Return a JSON representation of a Python string
    """
    return ""

之后转json的时候一定的注意这个问题

编码就是使用python中最常出现的问题,真是。。。

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 可以使用 Python 内置的 `json` 模块来实现。 首先,你需要导入 `json` 模块: ``` import json ``` 然后,你可以使用 `json.dumps()` 函数将字典转换为 JSON 字符串: ``` data = { "name": "John", "age": 30, "city": "New York" } json_str = json.dumps(data, ensure_ascii=False) print(json_str) ``` 输出结果: ``` {"name": "John", "age": 30, "city": "New York"} ``` `json.dumps()` 函数的第二个参数 `ensure_ascii` 用于控制是否以 ASCII 编码输出,如果设置为 `False`,则可以输出中文字符。 ### 回答2: Python中可以使用内置的json模块将字典格式转化JSON字符串。 首先,导入json模块: ```python import json ``` 然后,定义一个字典对象: ```python data = {'name': 'Alice', 'age': 25, 'city': 'New York'} ``` 接下来,使用json.dumps()方法将字典对象转化JSON字符串: ```python json_string = json.dumps(data) ``` 最后,可以打印输出JSON字符串: ```python print(json_string) ``` 以上代码将输出如下结果: ```python {"name": "Alice", "age": 25, "city": "New York"} ``` 另外,如果想要保留缩进或排序,可以在调用dumps()方法时传入额外的参数。例如,将缩进设置为4个空格: ```python json_string = json.dumps(data, indent=4) ``` 或者按照字母顺序排序键: ```python json_string = json.dumps(data, sort_keys=True) ``` 这样可以得到带有缩进或排序的JSON字符串。 需要注意的是,如果字典中的值包含了不支持JSON序列化的类型(如函数、类等),则会引发TypeError异常。 ### 回答3: 在Python中,可以使用内置的`json`模块将字典对象转换为JSON格式的字符串。使用`json.dumps()`方法可以将字典转换为JSON字符串。 下面是一个示例代码: ```python import json # 创建一个字典对象 person = { "name": "张三", "age": 25, "city": "北京" } # 将字典转换为JSON字符串 json_str = json.dumps(person) # 输出JSON字符串 print(json_str) ``` 运行代码后,将会输出以下内容: ```json {"name": "\u5f20\u4e09", "age": 25, "city": "\u5317\u4eac"} ``` 在输出结果中,你会看到字典的键和值已经被转换为相应的JSON格式。如果希望输出时中文字符正常显示,可以添加`ensure_ascii=False`参数,例如`json_str = json.dumps(person, ensure_ascii=False)`。 需要注意的是,如果字典中包含不支持JSON序列化的数据类型,如`datetime`对象,转换过程将会出错。在这种情况下,可以使用自定义的处理函数或类扩展`JSONEncoder`类来序列化这些特殊对象。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值