【问题标题】:Making a nested JSON from '/' delimited CSV headers从“/”分隔的 CSV 标头制作嵌套 JSON
【发布时间】: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 文件的样例吗?
  • 您对bashpython 标签的使用是由什么样的上下文支持的?
  • 欢迎来到 Stack Overflow。您显示的数据与所需输出之间的关系在逻辑上确实匹配。逗号分隔值 (CSV) 意味着使用 , 而不是 /。你能提供一个你的内容或数据的例子吗?
  • 感谢您指出这一点@HaiVu 我已经添加了一个数据示例以及一个反映某些人将职位组合用逗号分隔的示例。
  • 你有 Python 和 Javascript。您希望使用哪种语言完成此操作?

标签: python jquery node.js json bash


【解决方案1】:

这样做。有点难看,但是解析这些标头有一些奇怪的特殊情况。

import csv
import json

def process( headers, row ):
    gather = {}
    for h,r in zip(headers,row):
        cur = gather
        key = 'BASE'
        for p in h.split('/'):
            print(gather,cur, key,p)
            if p.isdigit():
                p = int(p)
                if key not in cur:
                    cur[key] = []
                if len(cur[key]) < p+1:
                    cur[key].append({})
            else:
                if isinstance(cur,dict) and key not in cur:
                    cur[key] = {}
            cur = cur[key]
            key = p
        cur[key] = r.strip()
    return gather['BASE']

fcsv = csv.reader(open('x.csv'))
headers = next(fcsv)

data = []
for row in fcsv:
    data.append( process( headers, row ) )
print(json.dumps(data,indent=4))

输出:

[
    {
        "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"
                }
            }
        ],
        "template_id": "Meat Grill"
    },
    {
        "from": {
            "email": "me@x.com",
            "name": "Me"
        },
        "to": [
            {
                "email": "lauren@y.com"
            }
        ],
        "personalization": [
            {
                "email": "lauren@y.com",
                "data": {
                    "first_name": "Lauren",
                    "company_name": "Y Inc.",
                    "job_title": "Bartender"
                }
            }
        ],
        "template_id": "12345"
    }
]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多