Skip to content
Advertisement

Converting a Dataframe into a specific json format

I need to convert this dataframe into the json format below and I can’t get it to work

conv_item_id updated_item_value order_check
a 1.99 approved
b 2.99 approved
c 2.99 approved
JavaScript

I currently have this function that converts the dataframe into a string

JavaScript

gives the following result as a string

JavaScript

I need the format to be

JavaScript

Does anyone have any idea how to do this? I’ve attempted to use strip and replace but it either only removes the final } or all of them.

Thanks in advance,

Advertisement

Answer

Example df:

JavaScript
  • set index to conv_item_id using df.set_index()
  • rename column names using df.rename()
  • Convert df to dict with index as keys using df.to_dict("index")
  • dump dict to json using json.dumps()
JavaScript
Advertisement