0

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"|
  },
1
  • how to get the same output in nested json format? I'm getting in this format.[ { "ADDRESS": "Others", "CITY": "Others", "COUNTRY": "Others" } ] But I want the output in nested json format like { "reviewer": { "city": "", "country": "" "address": "Orlando, Florida" }} Commented Mar 25, 2019 at 11:17

1 Answer 1

1

You're missing the separator parameter. Instead of:

reader = csv.DictReader(csvfile)

Use:

reader = csv.DictReader(csvfile, delimiter='|')
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. I got the json structure now.
How can I check for particular field value in the above program I have written. I have 2 fields 'recommendation' and 'rating'. Based on recommendation I need to set value for rating, like if recommendation is 1 then rating is 1 and vice versa
This is the link for other question. stackoverflow.com/questions/55333086/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.