Python JSON 转 CSV - 编码问题,UnicodeDecodeError: 'charmap' 编解码器无法解码字节

8
我有一个问题,需要将嵌套的JSON转换为CSV格式。为此,我使用了https://github.com/vinay20045/json-to-csv(稍作修改以支持Python 3.4),以下是完整的json-to-csv.py文件。 如果我设置...,则转换可以正常工作。
    #Base Condition
else:
    reduced_item[str(key)] = (str(value)).encode('utf8','ignore')

并且

fp = open(json_file_path, 'r', encoding='utf-8')

但是当我将csv导入MS Excel时,我看到了糟糕的西里尔字符,例如\xe0\xf1,英文文本是可以的。尝试使用encode('cp1251','ignore')设置,但后来出现了错误UnicodeDecodeError: 'charmap' codec can't decode byte X in position Y: character maps to(as here UnicodeDecodeError: 'charmap' codec can't decode byte X in position Y: character maps to <undefined>)。
import sys
import json
import csv

##
# This function converts an item like 
# {
#   "item_1":"value_11",
#   "item_2":"value_12",
#   "item_3":"value_13",
#   "item_4":["sub_value_14", "sub_value_15"],
#   "item_5":{
#       "sub_item_1":"sub_item_value_11",
#       "sub_item_2":["sub_item_value_12", "sub_item_value_13"]
#   }
# }
# To
# {
#   "node_item_1":"value_11",
#   "node_item_2":"value_12",
#   "node_item_3":"value_13",
#   "node_item_4_0":"sub_value_14", 
#   "node_item_4_1":"sub_value_15",
#   "node_item_5_sub_item_1":"sub_item_value_11",
#   "node_item_5_sub_item_2_0":"sub_item_value_12",
#   "node_item_5_sub_item_2_0":"sub_item_value_13"
# }
##
def reduce_item(key, value):
    global reduced_item

    #Reduction Condition 1
    if type(value) is list:
        i=0
        for sub_item in value:
            reduce_item(key+'_'+str(i), sub_item)
            i=i+1

    #Reduction Condition 2
    elif type(value) is dict:
        sub_keys = value.keys()
        for sub_key in sub_keys:
            reduce_item(key+'_'+str(sub_key), value[sub_key])

    #Base Condition
    else:
        reduced_item[str(key)] = (str(value)).encode('cp1251','ignore')


if __name__ == "__main__":
    if len(sys.argv) != 4:
        print("\nUsage: python json_to_csv.py <node_name> <json_in_file_path> <csv_out_file_path>\n")
    else:
        #Reading arguments
        node = sys.argv[1]
        json_file_path = sys.argv[2]
        csv_file_path = sys.argv[3]

        fp = open(json_file_path, 'r', encoding='cp1251')
        json_value = fp.read()
        raw_data = json.loads(json_value)

        processed_data = []
        header = []
        for item in raw_data[node]:
            reduced_item = {}
            reduce_item(node, item)

            header += reduced_item.keys()

            processed_data.append(reduced_item)

        header = list(set(header))
        header.sort()

        with open(csv_file_path, 'wt+') as f:#wb+ for python 2.7
            writer = csv.DictWriter(f, header, quoting=csv.QUOTE_ALL, delimiter=',')
            writer.writeheader()
            for row in processed_data:
                writer.writerow(row)

        print("Just completed writing csv file with %d columns" % len(header))

如何正确转换西里尔字母,同时我想跳过坏字符?

2个回答

14

你需要知道要打开的文件使用的 Cyrillic 编码方式。

例如,在 Python 3 中可以这样表示:

with open(args.input_file, 'r', encoding="cp866") as input_file:
        data = input_file.read()
        structure = json.loads(data)

在Python3中,数据变量自动采用UTF-8编码。在Python2中,输入JSON时可能会出现问题。

还可以尝试在Python解释器中打印一行,查看符号是否正确。没有输入文件很难确定一切是否正确。您确定这是Python的问题,而不是Excel相关的问题吗?您是否尝试过在Notepad++或其他支持编码的编辑器中打开文件?

使用编码处理数据时最重要的事情是检查输入和输出是否正确。建议查看此处。


3
澄清一下,那是我的错误:我从GitHub上编码时在两个地方添加了自己的编码设置,这是不正确的。所以答案是在下面这行代码中添加encoding="utf8":with open(args.input_file, 'r', encoding="cp866") as input_file: 然后文件将会在Excel中正确打开。 并且从(str(value)).encode('cp1251','ignore')和fp = open(json_file_path, 'r', encoding='cp1251')中删除编码声明。 - Vic Nicethemer

7
也许您可以使用chardet来检测文件的编码。
import chardet

File='arq.GeoJson'
enc=chardet.detect(open(File,'rb').read())['encoding']
with open(File,'r', encoding = enc) as f:
    data=json.load(f)
    f.close()

这可以避免对编码进行“踢出”。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接