Python和CSV:从CSV读取JSON
我有一个函数,可以读取CSV文件并将内容转储到所选文件。此csv文件的内容是一列,其中每行包含一系列JSON对象,如下所示(使用jsonlint验证): 为了概念化这一点,这就是我想要的:Python和CSV:从CSV读取JSON,python,json,csv,Python,Json,Csv,我有一个函数,可以读取CSV文件并将内容转储到所选文件。此csv文件的内容是一列,其中每行包含一系列JSON对象,如下所示(使用jsonlint验证): 为了概念化这一点,这就是我想要的: csv file ---> function that I wrote ---> something.json 在本例中,我使用test.csv作为输入,test.txt作为输出。对于第一个json流,它似乎工作得很好,但有一个怪癖: 第一个JSON对象很好地显示出来: [ {"classNa
csv file ---> function that I wrote ---> something.json
在本例中,我使用test.csv作为输入,test.txt作为输出。对于第一个json流,它似乎工作得很好,但有一个怪癖:
第一个JSON对象很好地显示出来:
[
{"className": "Merchant", "__type": "Pointer", "objectId": "S8IGOwBn8Y"},
{"className": "Merchant", "__type": "Pointer", "objectId": "psNnxwFVmv"},
{"className": "Merchant", "__type": "Pointer", "objectId": "IHcC9ikKBJ"}],
但在那之后,他们开始像这样出现:
"[{""className"": ""Merchant"", ""__type"": ""Pointer"", ""objectId"": ""S8IGOwBn8Y""},
{""className"": ""Merchant"", ""__type"": ""Pointer"", ""objectId"": ""psNnxwFVmv""},
{""className"": ""Merchant"", ""__type"": ""Pointer"", ""objectId"": ""IHcC9ikKBJ""},
{""className"": ""Merchant"", ""__type"": ""Pointer"", ""objectId"": ""RVprbh5nWx""},
{""className"": ""Merchant"", ""__type"": ""Pointer"", ""objectId"": ""47Zjn9RRov""},
{""className"": ""Merchant"", ""__type"": ""Pointer"", ""objectId"": ""CoGtlmGzyo""},
{""className"": ""Merchant"", ""__type"": ""Pointer"", ""objectId"": ""yJHn9dBCIT""},
{""className"": ""Merchant"", ""__type"": ""Pointer"", ""objectId"": ""nEOY9RPRD4""}',
'\n[{""className"": ""Merchant"", ""__type"": ""Pointer"", ""objectId"": ""tNgLB9dobR""},
以下是执行此操作的函数:
def read_csv(thefile):
f = open('test.txt','w')
with open(thefile, 'rb') as csvfile:
#based on python documentation
spamreader = csv.reader(csvfile, delimiter=']')
for row in spamreader:
f.write(str(row))
f.close()
两个问题:
import json
with open('test.txt','r') as input_file:
with open('output.json','wb') as output_file:
for row in input_file.readlines():
output_file.write(json.loads(row))
在任何情况下,使用此库都会对您有很大帮助:无法获取。。意味着您拥有CSV文件并创建JSON文件?我不创建.json文件。.json文件已创建,但为空。我有一个csv文件,其中每一行都是一系列JSON对象,以[开头,以]结尾。我的想法是,我想从这个csv文件中读取(逐行)并将这些值传递给一个.json文件。问题是,在读取第一行之后,后续的其他行被错误地读取。您的第一个文件似乎就是json。您是否可以尝试在读取json后
导入json
和json.loads(您的_文件)
(在您的代码中是json.loads(csvfile.read())
而不是使用csv.reader()
)?如果只有一列,为什么要将文件作为csv文件读取?为什么不使用json模块?是的,使用json模块
import json
with open('test.txt','r') as input_file:
with open('output.json','wb') as output_file:
for row in input_file.readlines():
output_file.write(json.loads(row))