1

I'm converting csv to newline delimited json with

import csv
import json

csvfile = open('input.csv', 'r')
jsonfile = open('output.json', 'w')

reader = csv.DictReader( csvfile, fieldnames)
for row in reader:
    json.dump(row, jsonfile)
    jsonfile.write('\n')

Input:

firstname,secondname,id,marks
John,Doe,001,50
George,Washington,002,100

Output:

{"firstname": "John", "secondname": "Doe", "id": "001", "marks": "50"}
{"firstname": "George", "secondname": "Washington", "id": "002", "marks": "100"}

Pretty good. But a search application I'm using rejects to upload the file because I already defined "marks" field as float in the schema. It accepts only if I remove quotation marks around the number field. So I require output to be:

Desired Output:

{"firstname": "John", "secondname": "Doe", "id": "001", "marks": 50}
{"firstname": "George", "secondname": "Washington", "id": "002", "marks": 100}

Is there a way I can specify a field as float/string while converting csv to json? (I can get away by remapping schema with marks as string, but I'll lose "sort by marks" option in the application).

sri sri
  • 15
  • 4

2 Answers2

0

Seeming a is one of your dictionaries, you can try:

for x in a.keys():
  if str(a[x]).isdigit():
    a[x] = int(a[x])
 
print(a)
Wasif
  • 14,755
  • 3
  • 14
  • 34
0

Converting one dict entry to float:

row["marks"] = float(row["marks"])

Integrated in your code:

for row in reader:
    row["marks"] = float(row["marks"])
    json.dump(row, jsonfile)
    jsonfile.write('\n')

Also see: How do I parse a string to a float or int?

Wups
  • 2,489
  • 1
  • 6
  • 17