0

my code :

import csv
import json
with open('file.csv', 'r') as f:
    reader = csv.reader(f, delimiter=';')
    data_list = list()
    for row in reader:
        data_list.append(row)
data = [dict(zip(data_list[0],row)) for row in data_list]
data.pop(0)
s = json.dumps(data, indent=2)
print (s)

Actual Result :

[
  {
    "bundleParentId": " ",
    "id": "1",
    "itemType": "ART",
    "itemNo": "90411111",
    "requiredQty": "2",
    "unitOfMeasure": "Piece"
  }
]

Expected Result ;

  {
    "bundleParentId": " ",
    "id": "1",
    "itemType": "ART",
    "itemNo": "90411111",
    "requiredQty": "2",
    "unitOfMeasure": "Piece"
  }
Kate Paulk
  • 31,513
  • 8
  • 54
  • 108

2 Answers2

3

You can use the "json.dump" and inside that use "for loop" which will create multiple objects in string (JSON format) till the reader reaches the last row.

For example:-

import csv
import json

csvfile_path = open('/home/Python/Data.csv', 'r')
jsonfile_path = open('/home/Python/Output.json', 'w')

field_name = ("Continent","Country","State","Capital")
reader = csv.DictReader( csvfile_path, field_name)
out = json.dumps( [ row for row in reader ] )
jsonfile_path.write(out)
Kate Paulk
  • 31,513
  • 8
  • 54
  • 108
Dhairya
  • 316
  • 2
  • 10
1

The problem you have here is the Json format. A csv file contains a set of values, which can be an array of one or more objects - and you are expecting one object only, not a set of objects.

You receive a [{}] format, because between the [] are the values, such as [{}, {}, {}...]. Try the following for each row you have in the csv file:

reader = csv.DictReader(csv,fields)
for row in reader:
    json.dump(row,jsonFile)
    jsonfile.write('\n')
MMMM
  • 361
  • 1
  • 5