Skip to content
Advertisement

Json to CSV file conversion using python

I have a sample JSON file like this

JavaScript

i need to take only specific key and values from the json file and convert it into a CSV file

Code: Ref:Extracting Specific Keys/Values From A Messed-Up JSON File (Python)

JavaScript

When I’m passing 2 values through the extract(), getting NaN in between result

JavaScript

I need to get an output like the below

JavaScript

and convert it into a csv file, can somebody help me to solve this issue

Advertisement

Answer

Your method seems ok to me. You are just making a mistake in the for key in keysloop: what you are currently doing is you are creating a single dict ({key: current[key]}) for every element. So at the end you will have a out list that is a list of dicts that are not related, in which each videoID is in a dict and type is in a different dict. Like this:

JavaScript

What you would want instead is:

JavaScript

where each videoID is related to its type.

To do so you just have to create a dict when looping on keys, add each element to the dict and then append the dict to out list at the end of the loop on keys.

What I would do is this:

JavaScript

so the whole extract function would become:

JavaScript

Finally, to write a dict in a csv file I would simply use csv DictWriter:

JavaScript

This would create a CSV with videoID and type columns Alternatively, as suggested by Ivan Calderon answer here you could also use pandas to_csv method in one line:

you should change your dictionary before:

JavaScript

but I am not sure about this…

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement