【问题标题】:how to correctly save "\u**" to json in python如何在python中正确地将“\u**”保存到json
【发布时间】:2017-01-24 01:49:08
【问题描述】:

我有一本字典:

data = {"data": "\u512b"}

当我将它转储到 json 时:

import json
print json.dumps(data)

我得到了:{"a":"\\u512b"} 我应该怎么做才能得到准确的{"a":"\u512b"}

注意:我尝试在字符串前添加u,使其变为u'\u512b',额外的\ 不会再次出现,请告诉我原因

【问题讨论】:

  • 你能改写I try to add u before the string and it works, please also tell me why,这句话我看不懂
  • also: json.dump(data) 不起作用,因为 json.dump 需要两个参数:一个对象和一个文件指针
  • @hansaplast 你提到的现在已经修复了,谢谢

标签: python json


【解决方案1】:

你可以做一些黑客攻击。

import json

data = {"data": "\u512b"}
s = json.dumps(data)
print(s.replace(r'\u', 'u'))
print(type(s.replace(r'\u', 'u')))

输出:

{"data": "\u512b"}
<type 'str'>

【讨论】:

    【解决方案2】:

    我的猜测是,您只是被 Python 解释器的输出弄糊涂了,它向您显示了 json.dumps 生成的字符串,并在字符串中的 \ 字符前面加上了自己的 \ 转义字符。 JSON 字符串作为值恰好包含一个 \,如您所愿 (IIUC):

    >>> data = {"data": "\u512b"}
    >>> data
    {'data': '\u512b'}
    >>> import json
    >>> json.dumps(data)
    '{"data": "\\u512b"}'
    >>> print(json.dumps(data))
    {"data": "\u512b"}
    >>> json.dump(data, open('data.json', 'w'))
    >>> ^Z
    C:\opt\Console2>type data.json
    {"data": "\u512b"}
    

    这实际上完全独立于 JSON,如下例所示:

    >>> s = "s\\u"
    >>> s
    's\\u'
    >>> print(s, len(s))   # length of s is 3, not 4
    s\u 3
    

    HTH!

    【讨论】:

      猜你喜欢
      • 2021-08-23
      • 2023-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-11
      • 2019-12-18
      • 2021-12-21
      相关资源
      最近更新 更多