How can I add extra value to my json output through python script

Viewed 52

Example: Desired output

{
    "id": "",
    "data": {
        "package": ""
    }
}

Here is the little script I have put together

import pandas as pd
df=pd.read_csv('example.csv')
df1=df[['request','text']]

dfnew=df1.rename(columns={'request':'id','text':'package'})
with open('something.json','w') as f:
    f.write(dfnew.to_json(orient='records',lines=True))

Output I receive after running the script

{"id":"","package":}
1 Answers

I'll start with a mock dfnew since the code above it does not affect your problem.

If Pandas does not have a built-in method to export exactly what you want, you can manually manipulate the JSON before dumping it to file:

import json

dfnew = pd.DataFrame({
    'id': [''],
    'package': ['']
})

with open('something.json', 'w') as f:
    jsonString = dfnew.to_json(orient='records', lines=True)
    jsonObject = json.loads(jsonString)
    package = jsonObject.pop('package')
    jsonObject['data'] = {
        'package': package
    }

    json.dump(jsonObject, f, indent=4)
Related