簡體   English   中英

Python JSON到CSV - 編碼錯誤,UnicodeDecodeError:'charmap'編解碼器無法解碼字節

[英]Python JSON to CSV - bad encoding, UnicodeDecodeError: 'charmap' codec can't decode byte

我在將嵌套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,英文文本就可以了。 實驗設置編碼('cp1251','忽略'),但后來我得到一個錯誤UnicodeDecodeError:'charmap'編解碼器無法解碼位置Y的字節X:字符映射到(因為這里UnicodeDecodeError:'charmap'編解碼器不能在位置Y解碼字節X:字符映射到<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))

如何正確轉換西里爾文,我還想跳過壞字符?

也許你可以使用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()

這避免了“踢”編碼。

您需要知道要打開哪個文件的cyrylic編碼。 例如,在python3中就足夠了:

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 ++或類似編碼來打開編輯器?

使用編碼最重要的是檢查輸入和輸出是否正確。 我建議看這里。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM