1

is there any easy way of converting below JSON format to CSV

JSON

{
"item1" : {
  "status":"Shipped",
  "Location":"TX",
  "trackingno":"z123345df234"
  },
"item2" : {
  "status":"OrderReceived",
  "Location":"AZ",
  "trackingno":"D234235dfawe98"
  }
}

Expected CSV

item1|Shipped|TX|z123345df234
item2|OrderReceived|AZ|D234235dfawe98
Panda
  • 97
  • 1
  • 9

1 Answers1

0

I would first convert the dictionary to a pandas Dataframe as follows:

df = pd.DataFrame([y[1] for y in u.items()], index = list(u.keys()))

So that if I print df, I get:

df

       Location status          trackingno
item1   TX      Shipped         z123345df234
item2   AZ      OrderReceived   D234235dfawe98

Then I would write the results to a csv as follows:

df.to_csv('NameOfMyDataFrame.csv', index = True)

I have put the index = True argument to ensure that you see the indices which are the items ['item1', 'item2'].

Samuel Nde
  • 2,565
  • 2
  • 23
  • 23
  • i was using item1 , item2 as examples in actual scenario they are different field names which are not related like below, so think we can't use a array ` code ` { "iphoneX" : { "status":"Shipped", "Location":"TX", "trackingno":"z123345df234" }, "Galaxy9" : { "status":"OrderReceived", "Location":"AZ", "trackingno":"D234235dfawe98" } } – Panda Oct 04 '18 at 06:31
  • I think this piece of code is very much general. – Samuel Nde Oct 04 '18 at 16:27