Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can i convert CSV in JSON like I want

Hello I show you my problem’s :

I right that for convert my csv in Json. But the résult is not exactly what I Want .

main.py

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import csv
 
filename ="forcebrute.csv"
 
# opening the file using "with"
# statement
with open(filename, 'r') as data:
  for line in csv.DictReader(data):
      print(line)

csv

name;price;profit

Action-1;20;5

Action-2;30;10

Action-3;50;15

Action-4;70;20

Action-5;60;17

result i have:

{'name;price;profit': 'Action-1;20;5'}

{'name;price;profit': 'Action-2;30;10'}

{'name;price;profit': 'Action-3;50;15'}

{'name;price;profit': 'Action-4;70;20'}

{'name;price;profit': 'Action-5;60;17'}

And I would like this result:

enter image description here

>Solution :

You will need to specify the column delimiter then you can use json.dumps() to give you the required output format

import csv
import json

with open('forcebrute.csv') as data:
    print(json.dumps([d for d in csv.DictReader(data, delimiter=';')], indent=2))

Output:

[
  {
    "name": "Action-1",
    "price": "20",
    "profit": "5"
  },
  {
    "name": "Action-2",
    "price": "30",
    "profit": "10"
  },
  {
    "name": "Action-3",
    "price": "50",
    "profit": "15"
  },
  {
    "name": "Action-4",
    "price": "70",
    "profit": "20"
  },
  {
    "name": "Action-5",
    "price": "60",
    "profit": "17"
  }
]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading