I have this dataframe
Year type Median_Home_Value
786252 2010 analyzed 11973.000
786253 2011 analyzed 12500.000
786254 2012 analyzed 13325.000
786255 2013 analyzed 14204.000
786256 2014 analyzed 14815.000
786257 2015 analyzed 15393.000
786258 2016 analyzed 15901.000
786259 2017 analyzed 16680.000
786260 2018 analyzed 17497.000
786261 2019 analyzed 18249.000
786262 2020 analyzed 19381.000
786263 2021 analyzed 20292.000
899389 2027 predicted 20718.132
899390 2024 predicted 21225.432
899397 2026 predicted 21103.680
899415 2025 predicted 20779.008
899481 2023 predicted 20941.344
I want to create a json object to represent this dataframe to be like this
{
median_home_value: [{year: 2010, value: 11973, type: analyzed}, {year: 2011, value: 12500, type: analyzed}, ....]
}
I tried to do something like this
d = {}
d['Median_Home_Value] = test_df[['Year', 'Median_Home_Value', 'type']].to_json()
but it does not give me the expected result, any suggestions are appreciated.
>Solution :
Convert the dataframe to dictionary representation then dump the records into json data:
import json
records = df.rename(columns={'Median_Home_Value': 'value'}).to_dict('records')
json_data = json.dumps({'median_home_value': records})
Result
{
"median_home_value": [
{
"Year": 2010,
"type": "analyzed",
"value": 11973.0
},
{
"Year": 2011,
"type": "analyzed",
"value": 12500.0
},
{
"Year": 2012,
"type": "analyzed",
"value": 13325.0
},
...
}