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
x
17
17
1
{
2
"conversion_items":{
3
"a":{
4
"item_value":1.99,
5
"status":"approved"
6
},
7
"b":{
8
"item_value":2.99,
9
"status":"approved"
10
},
11
"c":{
12
"item_value":2.99,
13
"status":"approved"
14
}
15
}
16
}
17
I currently have this function that converts the dataframe into a string
JavaScript
1
13
13
1
# build all our requests
2
def build_request(row):
3
return {
4
row["conv_item_id"]: {
5
"item_value": row["updated_item_value"],
6
"status" : str.lower(row["order_check"])
7
}
8
}
9
10
request_payload = df.apply(build_request, axis=1).to_json(orient='records')[1:-1].replace('}{', '} {')
11
12
df2 = {"conversion_items": request_payload}
13
gives the following result as a string
JavaScript
1
2
1
{'conversion_items': '{"a":{"item_value":1.99,"status":"approved"}},{"b":{"item_value":2.99,"status":"approved"}},{"c":{"item_value":2.99,"status":"approved"}}'}
2
I need the format to be
JavaScript
1
2
1
{'conversion_items': {"a":{"item_value":1.99,"status":"approved"},"b":{"item_value":2.99,"status":"approved"},"c":{"item_value":2.99,"status":"approved"}}
2
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
1
3
1
import pandas as pd
2
df = pd.DataFrame({"conv_item_id":["a","b","c"],"updated_item_value":[1.99,2.99,2.99],"order_check":["approved"]*3})
3
- 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
1
10
10
1
import json
2
df = df.set_index("conv_item_id")
3
df = df.rename(columns={"updated_item_value":"item_value","order_check":"status"})
4
out = json.dumps({"conversion_items": df.to_dict("index")})
5
print(out)
6
7
>> {'conversion_items': {'a': {'item_value': 1.99, 'status': 'approved'},
8
'b': {'item_value': 2.99, 'status': 'approved'},
9
'c': {'item_value': 2.99, 'status': 'approved'}}}
10