0

I'm trying to convert a CSV file into a jSON file in order to then inject it into a Firebase database.

csvfile = open('final_df_2.csv', 'r')
jsonfile = open('final_df_5.json', 'w')

reader = csv.DictReader(csvfile)

for row in reader:
    json.dump({row['ballID']: [{"colour": row['colour'], "radius":row['radius']}]}, jsonfile)
    jsonfile.write('\n')

Unfortunately, I keep getting an "End of File expected" error

Here's my JSON's output

{
    "001": [
        {
            "colour": "green",
            "radius": "199405.0"
        }
    ]
}
{
    "002": [
        {
            "colour": "blue",
            "radius": "199612.0"
        }
    ]
}

In addition, Firebase sends back an error when I try to import the JSON file saying "Invalid JSON files"

Stevenson
  • 83
  • 1
  • 10
  • 1
    This is not a valid json file. It is a jsonl file, i.e. each line is a valid json. See [here](https://stackoverflow.com/questions/50475635/loading-jsonl-file-as-json-objects) for more. – SamR Apr 06 '22 at 08:45

1 Answers1

1

You could collect all the data into a python list and dump that list to the json file:

csvfile = open('final_df_2.csv', 'r')

reader = csv.DictReader(csvfile)
jsoncontent = []
for row in reader:
    jsoncontent.append({row['ballID']: [{"colour": row['colour'], "radius":row['radius']}]})

with open('final_df_5.json', 'w') as jsonfile:
    json.dump(jsoncontent, jsonfile)

However, I'm not sure what your firebase database is expecting.

quamrana
  • 37,849
  • 12
  • 53
  • 71