Home > Blockchain >  How to get headers names from json data | python
How to get headers names from json data | python

Time:03-23

I am trying to convert json data to csv and I was able to do

But one main problem is I need to hard code my headers in list ... how to get automatically headers and even i am passing - jsdata['clients'] -> client hardcoded

Need to make generic the headers and client which I am passing

Code :

import json
import csv 

header = ["id","isActive","age","name","gender","company","email","phone","address"]
with open('/content/sample_data/ABC.json') as rd:
  jsdata = json.loads(rd.read())
  with open('/content/sample_data/Ts.csv','w') as wr:
    csv_wr = csv.DictWriter(wr,fieldnames=header)
    csv_wr.writeheader()
    csv_wr.writerows(jsdata['clients'])

Following is my json data

{
  "clients": [
    {
      "id": "59761c23b30d971669fb42ff",
      "isActive": true,
      "age": 36,
      "name": "Dunlap Hubbard",
      "gender": "male",
      "company": "CEDWARD",
      "email": "[email protected]",
      "phone": " 1 (890) 543-2508",
      "address": "169 Rutledge Street, Konterra, Northern Mariana Islands, 8551"
    },
    {
      "id": "59761c233d8d0f92a6b0570d",
      "isActive": true,
      "age": 24,
      "name": "Kirsten Sellers",
      "gender": "female",
      "company": "EMERGENT",
      "email": "[email protected]",
      "phone": " 1 (831) 564-2190",
      "address": "886 Gallatin Place, Fannett, Arkansas, 4656"
    },
    {
      "id": "59761c23fcb6254b1a06dad5",
      "isActive": true,
      "age": 30,
      "name": "Acosta Robbins",
      "gender": "male",
      "company": "ORGANICA",
      "email": "[email protected]",
      "phone": " 1 (882) 441-3367",
      "address": "697 Linden Boulevard, Sattley, Idaho, 1035"
    }
  ]
}

CodePudding user response:

If every dictionary within the clients list has the same keys then...

csv_wr = csv.DictWriter(wr,fieldnames=jsdata['clients'][0])
  • Related