Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
CSV to Json
#6
(Jul-11-2020, 03:17 AM)Larz60+ Wrote: 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


Thank you for looking at this - I have really struggled to create this json - unfortunately it is part of an existing api that I want to interact with.


unfortunately does not quite generate expected format

    "RecIds": [{
        "type": "A",
        "value": "x1"
    }, {
        "type": "B",
        "value": "y2"
    }]
RecIds can be one or more identifiers as per sample


Modding your example I can the basic structure but I encounter 3 problems:
  • blank value(I guess and if can take care of this),
  • invalid json due to the ' rather than "
  • and the embedded objects should be [] rather than {}


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('sample.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']
            dnode['type2'] = 'B'
            dnode['value2'] = row['B']
            rnode['source'] = row['source']
            rnode['status'] = row['status']
            rnode['recordType'] = row['RecordType']

            xnode = rnode['xIds'] = {}
            xnode['type'] = 'xA'
            xnode['value'] = row['xA']
            xnode['type2'] = 'xB'
            xnode['value2'] = row['xB']
            alldata.append(ddict)
        out=json.dumps(alldata, indent=4)
        f = open('jsonfile.json', 'w')
        f.write(out)

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