Home > database >  Pandas csv to json
Pandas csv to json

Time:08-31

I have this code i`ts work but i wont get another result

parser.add_argument('-f', '--fields', help='csv fields', type=lambda s: [str(item) for item in s.split(',')])
fields = parser.parse_args().fields
print(fields)
df = pd.read_csv('data/file.csv', usecols=fields)
print(df.to_json(orient='index'))

Run command python main.py --fields date,campaign,clicks

Result:

['date', 'campaign', 'clicks']

{"0":{"date":"2022-01-06","campaign":"retageting APAC","clicks":1}}

It should return the data in JSON format in a "data" envelope.

Need result:

['date', 'campaign', 'clicks']

{"data":[{"date":"2022-01-06","campaign":"retageting APAC","clicks":1}]}

How to do this?

CodePudding user response:

Create dictionary with orient='records' first and then convert to json by json.dumps:

import json

d = {"0":{"date":"2022-01-06","campaign":"retageting APAC","clicks":1}}
df = pd.DataFrame.from_dict(d, orient='index')

print({"data":df.to_dict(orient='records')})
{'data': [{'date': '2022-01-06', 'campaign': 'retageting APAC', 'clicks': 1}]}

print(json.dumps({"data":df.to_dict(orient='records')}))
{"data": [{"date": "2022-01-06", "campaign": "retageting APAC", "clicks": 1}]}
  • Related