Skip to content Skip to sidebar Skip to footer

Nested Json File Flattened And Stored As Csv

I'm trying to get a json file into csv format, here is a snippet of the json file(sample3.json) : { 'x' : { '-tst1' : { 'da' : '8C', 'd' : 'df4', 'h' : 0,

Solution 1:

I'm not sure what you want, but does this work for you?

import json
import pandas as pd

with open('sample3.json') as f: # this ensures opening and closing file
    a = json.loads(f.read())

data = a["x"]

df = pd.DataFrame(data)

print(df.transpose())

my output:

          d  da  h  i      s              t
-tst1   df4  8C  0  1  False  1501394756245-tst2  df&*  8C  0  0   True  1501394946296

you can then do:

df.transpose().to_csv('myfilename.csv')

in response to your comment, you could do:

import json
import pandas as pd

a = """{"z" : { "y" : { "x" : { "-v" : { "d1" : "8C:F", "d2" : "8.0", "t" : 3, "x" : 45 }, "-u" : { "d1" : "8C", "d2" : "8.00", "t" : 5, "x" : 45 } } } }}"""

js = json.loads(a)

print pd.DataFrame.from_dict(js['z']['y']['x'], orient='index')

(the json you posted was missing a }, but I assume that was a copy/paste error)

Post a Comment for "Nested Json File Flattened And Stored As Csv"