从JSON转换为CSV时的Python 3编码问题

时间:2017-04-03 22:18:23

标签: python json character-encoding ascii utf

Python3

我已经看过其他解决方案,但他们似乎没有涵盖我的情况。我一直负责编写一个脚本来获取JSON并将其转换为CSV文件。

我有很多这样的事情,但在写数据时遇到了问题。我收到的数据与撰写的数据不符。以下是一个例子。我迷失了如何保持编码。

我应该提一下,默认编码是UTF-8

输入:necesitará

输出:necesitará

import csv
import json
import sys
import sys
print(sys.getdefaultencoding())
stuff = open('data.json')

jsonStuff = json.loads(stuff.read(), encoding="utf-8")
with open('output.csv', 'w', newline='\n', encoding='utf-8') as csvfile:
    writer = csv.writer(csvfile, delimiter=",",quotechar='"',quoting=csv.QUOTE_MINIMAL)

    for element in jsonStuff:
        row = ""
        key = element['key']
        values = element['valuesRow']

        row = element['key']
        # values[0]['value'], values[1]['value'], values[2]['value'], values[3]['value'],

        writer.writerow([element['key'], values[3]['value']])

1 个答案:

答案 0 :(得分:0)

删除getCacheDir()中的encoding='utf-8'应该修复它。

data.json(utf-8):open('output.csv', 'w', newline='\n', encoding='utf-8')

以下......

{"first": "necesitará", "second": "bodø"}

...给出output.csv:import csv import json with open('data.json') as stuff, open('output.csv', 'w', newline='\n', encoding='utf-8') as csvfile: jsonStuff = json.loads(stuff.read(), encoding="utf-8") writer = csv.writer(csvfile, delimiter=",", quotechar='"', quoting=csv.QUOTE_MINIMAL) first = jsonStuff['first'] second = jsonStuff['second'] writer.writerow([first, second])

然而......

necesitará,bodø

...生成output.csv:import csv import json with open('data.json') as stuff, open('output.csv', 'w', newline='\n') as csvfile: jsonStuff = json.loads(stuff.read(), encoding="utf-8") writer = csv.writer(csvfile, delimiter=",", quotechar='"', quoting=csv.QUOTE_MINIMAL) first = jsonStuff['first'] second = jsonStuff['second'] writer.writerow([first, second])

那就是说。当您拥有necesitará,bodø时,没有理由使用json.loads(),并且您定义的大部分内容都是默认值。我只是......

json.load()