Home > Blockchain >  Dataframe or CSV to JSON object array
Dataframe or CSV to JSON object array

Time:01-02

This is probably an easy one for the python pros. So, please forgive my naivety.

Here is my data:

0  [email protected]   13239169023       jane        bo
1  [email protected]   13239169023       lane        ko
2  [email protected]   13239169023       john        do

Here is what I get as output:

[{"email":"[email protected]","phone_number":13239169023,"first_name":"jane","last_name":"bo"},{"email":"[email protected]","phone_number":13239169023,"first_name":"lane","last_name":"ko"},{"email":"[email protected]","phone_number":13239169023,"first_name":"john","last_name":"do"}]

My Code:

    df = pd.read_csv('profiles.csv')
    print(df)
    data = df.to_json(orient="records")
    print(data)

Output I want:

{"profiles":[{"email":"[email protected]","phone_number":13239169023,"first_name":"jane","last_name":"bo"},{"email":"[email protected]","phone_number":13239169023,"first_name":"lane","last_name":"ko"},{"email":"[email protected]","phone_number":13239169023,"first_name":"john","last_name":"do"}]}

Adding below does NOT work.

output = {"profiles": data}

It adds single quotes on the data and profiles in NOT in double quotes (basically NOT a valid JSON), Like so:

{'profiles': '[{"email":"[email protected]","phone_number":13239169023,"first_name":"jane","last_name":"bo"},{"email":"[email protected]","phone_number":13239169023,"first_name":"lane","last_name":"ko"},{"email":"[email protected]","phone_number":13239169023,"first_name":"john","last_name":"do"}]'}

CodePudding user response:

You can use df.to_dict to output to a dictionary instead of a json-formatted string:

import pandas as pd
df = pd.read_csv('data.csv')
data = df.to_dict(orient='records')
output = {'profiles': data}
print(output)

Returns:

{'profiles': [{'0': 1, '[email protected]': '[email protected]', '13239169023': 13239169023, 'jane': 'lane', 'bo': 'ko'}, {'0': 2, '[email protected]': '[email protected]', '13239169023': 13239169023, 'jane': 'john', 'bo': 'do'}]}

CodePudding user response:

I think I found a solution.

Changes:

data = df.to_dict(orient="records")
output = {}
output["profiles"] = data
  • Related