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"
  }
2
  • 2
    How is this related to SQA? Mar 26, 2019 at 15:50
  • we are writing system testing test cases using python, so it is related to SQA only Mar 27, 2019 at 14:31

2 Answers 2

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.