【发布时间】:2022-02-05 07:39:59
【问题描述】:
我的 CSV 标题看起来像
| from/email | from/name | to/0/email | personalization/0/email/ | personalization/0/data/first_name | personalization/0/data/company_name | personalization/0/data/job_title | template_id |
|---|---|---|---|---|---|---|---|
| me@x.com | Me | mike@x.com | mike@x.com | Mike | X Inc. | Chef, Meat Grill | 12345 |
| me@x.com | Me | lauren@y.com | lauren@y.com | Lauren | Y Inc. | Bartender | 12345 |
输出应该是:
[
{
"from": {
"email": "me@x.com",
"name": "Me"
},
"to": [
{
"email": "mike@x.com"
}
],
"personalization": [
{
"email": "mike@x.com",
"data": {
"first_name": "Mike",
"company_name": "X Inc.",
"job_title": "Chef, Meat Grill"
}
}
],
"template_id": "123456"
},
我试过了
csvjson input.csv output.csv
csvtojson input.csv output.csv
csv2json input.csv output.csv
python3 app.py
import csv
import json
def csv_to_json(csvFilePath, jsonFilePath):
jsonArray = []
#read csv file
with open(csvFilePath, encoding='utf-8') as csvf:
#load csv file data using csv library's dictionary reader
csvReader = csv.DictReader(csvf)
#convert each csv row into python dict
for row in csvReader:
#add this python dict to json array
jsonArray.append(row)
#convert python jsonArray to JSON String and write to file
with open(jsonFilePath, 'w', encoding='utf-8') as jsonf:
jsonString = json.dumps(jsonArray, indent=4)
jsonf.write(jsonString)
csvFilePath = r'outputt1.csv'
jsonFilePath = r'outputt1.json'
csv_to_json(csvFilePath, jsonFilePath)
node app.js
const CSVToJSON = require('csvtojson');
// convert users.csv file to JSON array
CSVToJSON().fromFile('outputt1.csv')
.then(from => {
// from is a JSON array
// log the JSON array
console.log(from);
}).catch(err => {
// log error if any
console.log(err);
});
所有输出都是单行 JSON 的一些变体,没有嵌套。请帮忙。
【问题讨论】:
-
你有你的 csv 文件的样例吗?
-
您对
bash和python标签的使用是由什么样的上下文支持的? -
欢迎来到 Stack Overflow。您显示的数据与所需输出之间的关系在逻辑上确实匹配。逗号分隔值 (CSV) 意味着使用
,而不是/。你能提供一个你的内容或数据的例子吗? -
感谢您指出这一点@HaiVu 我已经添加了一个数据示例以及一个反映某些人将职位组合用逗号分隔的示例。
-
你有 Python 和 Javascript。您希望使用哪种语言完成此操作?
标签: python jquery node.js json bash