Search code examples
jsonpython-3.xcsvjsonconvert

How to convert json to csv with single header and multiple values?


I have input

data = [
  {
    "details": [
      {
        "health": "Good",
        "id": "1",
        "timestamp": 1579155574
      },
      {
        "health": "Bad",
        "id": "1",
        "timestamp": 1579155575
      }
    ]
  },
  {
    "details": [
      {
        "health": "Good",
        "id": "2",
        "timestamp": 1588329978
      },
      {
        "health": "Good",
        "device_id": "2",
        "timestamp": 1588416380
      }
    ]
  }
]

Now I want to convert it in csv something like below,

id,health
1,Good - 1579155574,Bad - 1579155575
2,Good - 1588329978,Good - 1588416380

Is this possible? Currently I am converting this in simple csv, my code and response are as below,

f = csv.writer(open("test.csv", "w", newline=""))

f.writerow(["id", "health", "timestamp"])
for data in data:
        for details in data['details']:
            f.writerow([details['id'],
                        details["health"],
                        details["timestamp"],
                        ])

Response:

id,health,timestamp
1,Good,1579155574
1,Bad,1579155575
2,Good,1579261319
2,Good,1586911295

So how could I get the expected output? I am using python3.


Solution

  • You almost have done your job, I think you do not need use csv module.

    And CSV does not mean anything, it just a name let people know what it is. CSV ,TXT and JSON are same things to computers, they are something to record the words.

    I don't know whole patterns of your datas, but you can get output value you want.

    output = 'id,health\n'
    for data in datas:
        output += f'{data["details"][0]["id"]},'
        for d in data["details"]:
            if 'health' in d:
                output += f'{d["health"]} - {d["timestamp"]},'
            else:
                output += f'{d["battery_health"]} - {d["timestamp"]},'
        output = output[:-1] + '\n'
    
    with open('test.csv', 'w') as op:
       op.write(output)