【发布时间】: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 字符,包括
a和q。) -
这个问题最好改写为“我如何解码 unicode”——答案很可能取决于 Windows 上 cmd shell 中的当前代码页(如果你在那个“操作系统”)。
-
json.load()给你一个字典,你用这个字典做的一切都与 JSON 无关,因为字典可以来自任何地方。现在,我不清楚的是为什么您甚至尝试将 dict 转换为字符串以及您想用它来实现什么。 -
问题已更新以解决两个 cmets。谢谢。
标签: python json python-2.7 unicode