Python JSON dataframe.to_json() output needs fixing

Question:

I’m trying to see if Out-of-the-Box a way to get JSON file created as per Requirements without having me to re-open JSON file and massage it further. The json array output I get from df.to_json("file", orient=’index’, indent=2, date_format=’iso’) has "0", "1", "3" etc as looks like elements root object names. Requirement is not to have those. And Secondly need to name Root Object.

CSV FILE (INPUT)
(https://i.stack.imgur.com/6gDZz.png)](https://i.stack.imgur.com/6gDZz.png)
vendor issuer
honda.com DigiCert
toyota.com GoDaddy

import pandas as pd
df = pd.read_csv('test_input.csv', na_filter=False, skiprows=0)
df.to_json("test_out.json", orient='index', indent=2, date_format='iso')

OUTPUT

{
  "0":{
    "vendor":"honda-us.com",
    "issuer":"Amazon",
    "licensed":"10/11/2021 16:14",
    "expiring":"2/9/2023 16:14",
    "remaining":57
  },

EXPECTING OUTPUT TO BE

{
  "vendorslist": [
   {
    "vendor":"honda-us.com",
    "issuer":"Amazon",
    "licensed":"10/11/2021 16:14",
    "expiring":"2/9/2023 16:14",
    "remaining":57
   }
 ]
},
Asked By: alisyed

||

Answers:

My recommendation would be somewhat build this yourself.

import json

import pandas as pd

df = pd.read_csv('test_input.csv', na_filter=False, skiprows=0)
data = {"vendorslist": df.to_dict(orient='records')}

with open("test_out.json", "w") as f:
    json.dump(data, f, indent=2, default=str)

This may not give you the exact answer you’re after, but it should be a good starting point 🙂

Answered By: kmiller96
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.