Need help converting JSON to CSV in Python? Best methods for 'python json to csv'?

16 Replies, 1407 Views

Nested JSON is the worst, right? For *python json to csv*, I use a combo of pandas and a custom function to flatten the JSON.

Here’s a snippet:

```python
import pandas as pd

def flatten_json(y):
out = {}
def flatten(x, name=''):
if type(x) is dict:
for a in x:
flatten(x[a], name + a + '_')
elif type(x) is list:
i = 0
for a in x:
flatten(a, name + str(i) + '_')
i += 1
else:
out[name[:-1]] = x
flatten(y)
return out

data = [flatten_json(d) for d in your_json_data]
df = pd.DataFrame(data)
df.to_csv('output.csv', index=False)
```

It’s a bit extra, but it handles even the messiest JSON.

Messages In This Thread



Users browsing this thread: 1 Guest(s)