Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
CSV to Json
#5
I think this is close if not there:
import os
import csv
import json


def csv_to_json():
    alldata = []
    ddict = {}
    # Excpect input file in same directory as this script, so set cwd
    os.chdir(os.path.abspath(os.path.dirname(__file__)))
    with open('csvfile.csv') as fp, open('jsonfile.json', 'w') as fo:
        crdr = csv.DictReader(fp)
        for row in crdr:
            rnode = ddict = {}
            dnode = rnode['RecIds'] = {}
            dnode['type'] = 'A'
            dnode['value'] = row['A']
            
            rnode['source'] = row['source']
            rnode['status'] = row['status']
            rnode['recordType'] = row['RecordType']

            xnode = rnode['xIds'] = {}
            xnode['type'] = 'B'
            xnode['value'] = row['B']
            alldata.append(ddict)
        json.dump(alldata, fo)

def read_it_back_as_dict():
    with open('jsonfile.json') as fp:
        mydict = json.load(fp)
    print(mydict)


if __name__ == '__main__':
    csv_to_json()
    read_it_back_as_dict()
results:
Output:
[{ "RecIds": { "type": "A", "value": "q1" }, "source": "Direct", "status": "New", "recordType": " Quote", "xIds": { "type": "B", "value": ""} }, { "RecIds": { "type": "A", "value": "x1" }, "source": "Direct", "status": "New", "recordType": " Quote", "xIds": { "type": "B", "value": "y2" } }]
I think this is a way overly complicated json format and makes for extra work in deciphering.
It's always good to kkeep it simple
Reply


Messages In This Thread
CSV to Json - by starfish - Jul-08-2020, 07:25 PM
RE: CSV to Json - by Larz60+ - Jul-08-2020, 08:51 PM
RE: CSV to Json - by starfish - Jul-08-2020, 09:24 PM
RE: CSV to Json - by starfish - Jul-10-2020, 06:56 PM
RE: CSV to Json - by Larz60+ - Jul-11-2020, 03:17 AM
RE: CSV to Json - by starfish - Jul-11-2020, 11:10 PM
RE: CSV to Json - by starfish - Jul-18-2020, 10:26 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020