【问题标题】:How do I decode unicode characters via python?如何通过 python 解码 unicode 字符?
【发布时间】:2015-11-01 09:11:31
【问题描述】:

我正在尝试使用 python 导入以下 json 文件:

文件名为new_json.json

{ "nextForwardToken": "f/3208873243596875673623625618474139659", "events": [ { "ingestionTime": 1045619, "timestamp": 1909000, "message": "2 32823453119 eni-889995t1 54.25.64.23 156.43.12.120 3389 23 6 342 24908 143234809 983246 ACCEPT OK" }] }

我有以下代码来读取 json 文件,并删除 unicode 字符:

JSON_FILE = "new_json.json"
with open(JSON_FILE) as infile:
    print infile
    print '\n type of infile is \n', infile
    data = json.load(infile)
    str_data = str(data)  # convert to string to remove unicode characters
    wo_unicode = str_data.decode('unicode_escape').encode('ascii','ignore')
    print 'unicode characters have been removed \n'
    print wo_unicode

print wo_unicode 仍会在其中打印 unicode 字符(即u)。

在尝试将 json 视为字典时,unicode 字符会导致问题:

for item in data:
    iden = item.get['nextForwardToken']

...导致错误:

AttributeError: 'unicode' object has no attribute 'get'

这必须在 Python2.7 中工作。有没有简单的方法解决这个问题?

【问题讨论】:

  • unicode 是什么问题?
  • "如何通过 python 去除 json 文件中的 unicode 字符?" 让文件完全为空,这是唯一的办法。 (提示:所有字符都是 Unicode 字符,包括 aq。)
  • 这个问题最好改写为“我如何解码 unicode”——答案很可能取决于 Windows 上 cmd shell 中的当前代码页(如果你在那个“操作系统”)。
  • json.load() 给你一个字典,你用这个字典做的一切都与 JSON 无关,因为字典可以来自任何地方。现在,我不清楚的是为什么您甚至尝试将 dict 转换为字符串以及您想用它来实现什么。
  • 问题已更新以解决两个 cmets。谢谢。

标签: python json python-2.7 unicode


【解决方案1】:

该错误与unicode无关,您试图将键视为dicts,只需使用data获取'nextForwardToken'

print data.get('nextForwardToken')

当您迭代 data 时,您正在迭代键,因此 'nextForwardToken'.get('nextForwardToken')"events".get('nextForwardToken') 等即使使用正确的语法显然也无法工作。

无论你是通过data.get(u'nextForwardToken')还是data.get('nextForwardToken')访问,都将返回key的值:

In [9]: 'nextForwardToken' == u'nextForwardToken'
Out[9]: True
In [10]: data[u'nextForwardToken']
Out[10]: u'f/3208873243596875673623625618474139659'   
In [11]: data['nextForwardToken']
Out[11]: u'f/3208873243596875673623625618474139659'

【讨论】:

    【解决方案2】:

    此代码将为您提供不带 unicode 的 str 值

    import json
    JSON_FILE = "/tmp/json.json"
    with open(JSON_FILE) as infile:
        print infile
        print '\n type of infile is \n', infile
        data = json.load(infile)
        print data
        str_data = json.dumps(data)
        print str_data
    

    【讨论】:

      猜你喜欢
      • 2011-04-21
      • 2018-09-21
      • 2019-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      • 2020-03-30
      相关资源
      最近更新 更多