Python 使用双引号将JSON数组转换为CSV
我想将JSON数组转换为CSV文件。这是因为我想生成一个数据集,我可以在API上使用JMeter测试我的API是否足够强大,可以同时处理多个请求 通常,只要我将数组导入CSV,数组就会出现一个单引号,这样API就不会将其作为有效的JSON。当我使用Python 使用双引号将JSON数组转换为CSV,python,arrays,json,csv,Python,Arrays,Json,Csv,我想将JSON数组转换为CSV文件。这是因为我想生成一个数据集,我可以在API上使用JMeter测试我的API是否足够强大,可以同时处理多个请求 通常,只要我将数组导入CSV,数组就会出现一个单引号,这样API就不会将其作为有效的JSON。当我使用json.dumps(array)时,数组将被放置在CSV文件中,如右图所示,这也是不正确的“[”726102”“]” 我希望我的数组:['726102']以这种方式->[“726102”]在CSV文件中,以便我可以用JMeter读取它 现在的结果是:
json.dumps(array)
时,数组将被放置在CSV文件中,如右图所示,这也是不正确的“[”726102”“]”
我希望我的数组:['726102']
以这种方式->[“726102”]
在CSV文件中,以便我可以用JMeter读取它
现在的结果是:
array
"[""726102""]"
但我所期望的是:
array
["726102"]
这就是如何将JSON数据转换为CSV
import json
import csv
# Opening JSON file and loading the data
# into the variable data
with open('data.json') as json_file:
data = json.load(json_file)
employee_data = data['emp_details']
# now we will open a file for writing
data_file = open('data_file.csv', 'w')
# create the csv writer object
csv_writer = csv.writer(data_file)
# Counter variable used for writing
# headers to the CSV file
count = 0
for emp in employee_data:
if count == 0:
# Writing headers of CSV file
header = emp.keys()
csv_writer.writerow(header)
count += 1
# Writing data of CSV file
csv_writer.writerow(emp.values())
data_file.close()
谢谢json。dumps(array)
提供一个字符串'[“726102”]
当将其放入CSV时,它会被括在引号中,因为整个内容都是一个字段,所以您会得到以下字符串:“[“726102”]”
此外,由于字符串包含引号。因此,每个引号都被两个引号替换,最终您将得到“[”“726102”“]”
您确定需要使用
json.dumps
将看起来像一个简单列表的内容字符串化,并将其写入一个“csv”中,该“csv”似乎每行只包含一个值吗?您可以在创建时显式设置两个csv.DictWriter
实例,以便它能够处理json.dumps()的输出
results.csv
文件的内容:
数组
["726102"]
请再次检查我的问题。谢谢您的评论,我用一些代码更新了我的问题:-)在玩了一会儿之后,我有类似的问题。OP似乎试图将数组写入CSV中的单元格,而CSV文件的使用方式并非如此。我认为OP真正想要的是CSV文件的每一行包含源JSON中每个数组的元素。现在由OP来为这些元素命名字段(如果确实需要标题,这也不清楚)。
import json
import csv
# Opening JSON file and loading the data
# into the variable data
with open('data.json') as json_file:
data = json.load(json_file)
employee_data = data['emp_details']
# now we will open a file for writing
data_file = open('data_file.csv', 'w')
# create the csv writer object
csv_writer = csv.writer(data_file)
# Counter variable used for writing
# headers to the CSV file
count = 0
for emp in employee_data:
if count == 0:
# Writing headers of CSV file
header = emp.keys()
csv_writer.writerow(header)
count += 1
# Writing data of CSV file
csv_writer.writerow(emp.values())
data_file.close()
import csv
import json
array = ["726102"]
with open('result.csv', 'w', newline='', encoding="utf-8") as file:
fieldnames = ["array"]
writer = csv.DictWriter(file, fieldnames=fieldnames,
quoting=csv.QUOTE_NONE, quotechar='\\') # ADDED
writer.writeheader()
writer.writerow({'array': json.dumps(array)})
# Display results.
with open('result.csv', 'r', encoding="utf-8") as file:
for line in file:
print(line.rstrip())