I want to create a dictionary using the values in a csv file and values defined in the code.
Then need to write that into a json file.
The image in the below link shows the data in the csv when attached to a df.
Below link contains the data I used in the csv file https://docs.google.com/spreadsheets/d/1RW9yZUWLHGXwRAxiOUchK8UkycMg2WfrX9DZwHNTjEY/edit?usp=drive_web&ouid=112366564296100909730
I used the following code.
import json
import pandas as pd
df = pd.read_csv('text.csv')
dict = {}
for index, row in df.iterrows():
a = "aaa"
u = "uuu"
g = str(row['animal'])
h = str(row['characteristic'])
dict.update({
"journal": [
[f"{a}",f"{g}"],
[f"t_s{u}",f"{h}"]
]})
with open('web.json', 'a') as file:
json.dump(dict, file)
file.write('n')
Above gave the output as below in ‘web.json’ file:
{"journal": [["aaa", "dog"], ["t_suuu", "four legs"]]}
{"journal": [["aaa", "cat"], ["t_suuu", "four legs"]]}
{"journal": [["aaa", "cow"], ["t_suuu", "four egs"]]}
{"journal": [["aaa", "bird"], ["t_suuu", "two legs"]]}
{"journal": [["aaa", "ant"], ["t_suuu", "six legs"]]}
2
Answers
Instead of using
dict
to record data and saving to JSON file on every loop, useList
and append the object to the list on each loop. After loop exits, dump that list of data (array of objects) to JSON file.You can try the following code
As @pratik-ghodke mentioned you should be using a
List
instead ofdict
to store the data and then dump theList
to the json file.The code above will store the data to web.json file in the following format