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"
  }

closed as off-topic by Rsf, Niels van Reijmersdal, c32hedge, NarendraC, trashpanda Mar 27 at 10:27

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Questions about software development unrelated to testing are off-topic here, but can be asked on Stack Overflow." – Rsf, Niels van Reijmersdal, c32hedge, NarendraC, trashpanda
If this question can be reworded to fit the rules in the help center, please edit the question.

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