I need to convert data from my csv
file to the one i am gonna use which is .js
.
Lp.;Name;Surname;Desc;Unit;Comment
1;Jan;Makowski;Inf;km;
2;Anna;Nowak;Pts;km;Brak reakcji
If you can see column 'comment'
does not always have record and I need to keep it that way. Also between data there is amount of tabs I need to set as well.
I've a file,i am working on right now but It show's me data in row like :
[{"Lp.;Name;Surname;Desc;Unit;Comment": "1;Jan;Makowski;Inf;km;"}, {"Lp.;Name;Surname;Desc;Unit;Comment": "2;Anna;Nowak;Pts;km;Brak reakcji"...]
I am new to python and I have no idea how to define what I need to get.
@@ Edit I managed to do that...
import json
import csv
# Deklaracja danych
fieldnames = ("Lp.", "Name", "Surname", "Desc", "Unit", "Comment")
# Otwieranie plików
with open('file.csv', 'r', encoding = "utf8") as csvfile:
reader = csv.DictReader(csvfile) # ,fieldnames)
rows = list(reader)
# Zamykamy plik
csvfile.close()
# Tworzymy plik z danych
with open('file.json', 'w', encoding = "utf8") as jsonfile:
json.dump(rows,jsonfile)
# jsonfile.write(s.replace(';', '/t'))
# Zamykamy plik
csvfile.close()
Pandas has both built-in .read_csv() and .to_json(). As an intermediate you get then a dataframe with which you can manipulate the data, including defining an index or data model.
I think this is your answer, this may not be the best way to do it, but it can gives you the result.
output:
You can minimize your script quite a lot given a few details of python:
The details about why this works:
This will create a list in memory with a dict for each row in the csv-file which might be worth keeping in mind if you are handling very large files. Sadly it isn't possible as far as I know to send the iterator directly to the json serializer without modifying the iterator or the serializer.
I'll leave the argument about which solution that is better from a maintenance and a readability perspective as an exercise for the reader.
A very quick example of solution:
Rather than writing a script, you could try the csvjson command line tool (written in Python):
http://csvkit.readthedocs.io/en/1.0.2/scripts/csvjson.html?highlight=csvjson