簡體   English   中英

從“/”分隔的 CSV 標頭制作嵌套的 JSON

[英]Making a nested JSON from '/' delimited CSV headers

我的 CSV 標頭看起來像

來自/電子郵件 來自名字 到/0/電子郵件 個性化/0/電子郵件/ 個性化/0/data/first_name 個性化/0/數據/公司名稱 個性化/0/data/job_title 模板編號
我@x.com 邁克@x.com 邁克@x.com 麥克風 X公司 廚師, 烤肉 12345
我@x.com lauren@y.com lauren@y.com 勞倫 Y公司 調酒師 12345

Output 應該是:

[
 {
   "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);
    });

所有 output 單行 JSON 的一些變體,沒有嵌套。 請幫忙。

這樣做。 這有點難看,但是解析這些標頭有一些奇怪的特殊情況。

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))

Output:

[
    {
        "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"
    }
]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM