1

I have following python script to read csv file and save its data to json file.

import csv
import json
import sys

with open(sys.argv[1], 'r') as csv_file:
    csv_content = csv.DictReader(csv_file)   
    with open(sys.argv[2], 'w') as new_file:
        new_file.write('[\n')
        for row in csv_content:
            json.dump(row, new_file)
            new_file.write(',\n')
        new_file.write(']')

Which works for English characters but throws exception to Devanagari characters.

Then I had changed my code to

import csv
import json
import sys

with open(sys.argv[1], encoding='utf-8', mode='r') as csv_file:
    csv_content = csv.DictReader(csv_file)   
    with open(sys.argv[2], encoding='utf-8', mode='w') as new_file:
        new_file.write('[\n')
        for row in csv_content:
            json.dump(row, new_file)
            new_file.write(',\n')
        new_file.write(']') 

Which generated

id,name,alpha2,alpha3
524,नेपाल,np,npl

to

{"\ufeffid": "524", "name": "\u0928\u0947\u092a\u093e\u0932", "alpha2": "np", "alpha3": "npl"},

Basically what I want is

{"id": "524", "name": "नेपाल", "alpha2": "np", "alpha3": "npl"},

as a result.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Albert Einstein
  • 7,472
  • 8
  • 36
  • 71

0 Answers0