In my Python code, I have a for loop that generates flattened JSON files.
I would like to append these JSON files recursively to a file (for example a .csv file) using the same for loop.
my final .csv should look like this:
{"name": "John", "age": 30, "married": true, "divorced": false, "children": ["Ann", "Billy"], "pets": null, "cars": [{"model": "BMW 230", "mpg": 27.5}, {"model": "Ford Edge", "mpg": 24.1}]}
{"name": "Doe", "age": 33, "married": true, "divorced": false, "children": ["Peter", "Billy"], "pets": null, "cars": [{"model": "Tesla", "mpg": 27.5}, {"model": "Ford Edge", "mpg": 27.1}]}
{"name": "Kurt", "age": 13, "married": true, "divorced": false, "children": ["Bruce", "Nikola"], "pets": null, "cars": [{"model": "Mercedes", "mpg": 27.5}, {"model": "123", "mpg": 24.1}]}
3
Answers
I found a way to do it. I was already testing but I was doing something wrong:
This part of the code is within the FOR-loop that creates flattened JSON files. Perhaps there are more elegant ways to do it, but it works.
You can install and import pandas, then use a ‘.to_csv()’.
For ex.:
You can find the documentation here -> pandas.pydata.org
The solution is to add all your data into a dictionary or other data structure like a list.
After that use the
csv
library to write a proper CSV file.https://docs.python.org/3/library/csv.html
Tha will look like this.
I would use
;
considering you have a list of names separated by,
.But why not write it all in a JSON file instead of a CSV.
A CSV will look like this.
It is preferred to store it all in a JSON, so you can keep the data schema.
Anyways you need to store your data in a dict or a list and then write it to a JSON file with
json
libraryhttps://docs.python.org/3/library/json.html
The json file will look like you said.