0

I know this question has been asked many times. I tried several solutions but I couldn't solve my problem.

I have a nested JSON file and I would like to convert it to a CSV file.

The JSON structure is like this:

[
  {
    "audio_analysis": [
      {
        "audio_percentage": 0.10006836243325763,
        "audio_completed": false,
        "audio_fast_forwarded": false,
        "audio_rewinded": false,
        "episode_downloaded": true,
        "listened_episode_time": 1799,
        "episode": 1,
        "elapsed_time": 1799,
        "location": {
          "": ""
        }
      },
      {
        "audio_percentage": 0.10290520872791918,
        "audio_completed": false,
        "audio_fast_forwarded": true,
        "audio_rewinded": true,
        "episode_downloaded": true,
        "listened_episode_time": 1850,
        "episode": 1,
        "elapsed_time": 1850,
        "location": {
          "": ""
        }
      }
    ],
    "correct_answers": 1,
    "count_completed_episodes": 0,
    "count_downloaded_episodes": 2,
    "total_time_spent_listening": 3649,
    "season": "Tiraarka Qoyska - Taxanaha 1aad",
    "user": "Joseph Kimani"
  }
]

The desired output should in the format attached on the below link.

csv output

  • 1
    Possible dupe, https://stackoverflow.com/questions/41180960/convert-nested-json-to-csv-file-in-python – sushanth Jul 07 '20 at 06:54

1 Answers1

0

pandas.normalize() to set the record (record_path ) and the other columns (meta).

data = pd.json_normalize(data, record_path='audio_analysis', meta=['correct_answers','count_completed_episodes','count_downloaded_episodes','total_time_spent_listening','season','user'])
data.to_csv('filename.csv')

    audio_percentage    audio_completed audio_fast_forwarded    audio_rewinded  episode_downloaded  listened_episode_time   episode elapsed_time    location.   correct_answers count_completed_episodes    count_downloaded_episodes   total_time_spent_listening  season  user
0   0.100068    False   False   False   True    1799    1   1799        1   0   2   3649    Tiraarka Qoyska - Taxanaha 1aad Joseph Kimani
1   0.102905    False   True    True    True    1850    1   1850        1   0   2   3649    Tiraarka Qoyska - Taxanaha 1aad Joseph Kimani
r-beginners
  • 31,170
  • 3
  • 14
  • 32