Home:ALL Converter>converting csv file into json format in python

converting csv file into json format in python

Ask Time:2019-03-25T14:11:19         Author:megsh

Json Formatter

I have written a code to convert my csvfile which is '|' delimited file to get specific json format.

Csv file format:

comment|address|city|country
crowded|others|others|US
pretty good|others|others|US .... 

I have tried with other codes as well since I'm new to python I'm stuck in between. If somebody helps me to correct the mistake I'm doing it would be helpful.

import csv
import json
from collections import OrderedDict

csv_file = 'test.csv'
json_file = csv_file + '.json'


def main(input_file):
    csv_rows = []
    with open(input_file, 'r') as csvfile:
        reader = csv.DictReader(csvfile)
        title = reader.fieldnames
        for row in reader:
            entry = OrderedDict()
            for field in title:
                entry[field] = row[field]
            csv_rows.append(entry)

    with open(json_file, 'w') as f:
        json.dump(csv_rows, f, sort_keys=True, indent=4, ensure_ascii=False)
        f.write('\n')


if __name__ == "__main__":
    main(csv_file)

I want in json format as below

{ 
 "reviewer": {
    "city": "",
    "country": ""   
    "address": "Orlando, Florida"
  },

But I'm getting output like this:

[
  {
    "COMMENT|\"ADDRESS\"|\"CITY\"|"COUNTRY":"Crowded"|"Others"|"Others"|
  },
  {
    "COMMENT|\"ADDRESS\"|\"CITY\"|"COUNTRY":"pretty good"|"Others"|"Others"|
  },

Author:megsh,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/55332115/converting-csv-file-into-json-format-in-python
yy