API的Python #datas
plan_get = pd.DataFrame(rows, columns=columns) #plan_get return all json data
return Response({"MESSAGE": "FOUND","DATA":json.loads(plan_get.to_json(orient='records'))})
实际输出
[{
"customer_name": "ABI2",
"location_name": "Cherai2",
"employee_name": "ASU2",
"Sales_Plan_Details": "[{\"Month\": \"2019-1\", \"Quantity\": 10, \"Product_Gid\": 3}]"
},
{
"customer_name": "ABI",
"location_name": "Cherai",
"employee_name": "ASU",
"Sales_Plan_Details": "[{\"Month\": \"2019-1\", \"Quantity\": 10, \"Product_Gid\": 3}]"
}]
预期输出:
[{
"customer_name": "ABI2",
"location_name": "Cherai2",
"employee_name": "ASU2",
"Sales_Plan_Details": [{"Month": "2019-1",
"Quantity": 10, "Product_Gid": 3}]
},
{
"customer_name": "ABI",
"location_name": "Cherai",
"employee_name": "ASU",
"Sales_Plan_Details": [{"Month": "2019-1",
"Quantity": 10, "Product_Gid": 3}]
}]
在这里,我正在使用pandas DataFrame传递json数据。我的问题是我如何在返回之前将Sales_Plan_Details(column)转换为json对象。
答案 0 :(得分:1)
您可以使用list comprehensions来映射Sales_Plan_Details
的值。
您可以使用json.loads()从字符串中反序列化列表值。
import json
dataframe_json = [
{
"customer_name": "ABI2",
"location_name": "Cherai2",
"employee_name": "ASU2",
"Sales_Plan_Details": "[{\"Month\": \"2019-1\", \"Quantity\": 10, \"Product_Gid\": 3}]"
},
{
"customer_name": "ABI",
"location_name": "Cherai",
"employee_name": "ASU",
"Sales_Plan_Details": "[{\"Month\": \"2019-1\", \"Quantity\": 10, \"Product_Gid\": 3}]"
}]
# get the "Sales_Plan_Details" key value's from the list
sales_plan_details_nested_list = [sales_plan_details_dict for sales_plan_details_dict in json.loads(item("Sales_Plan_Details")) for item in dataframe_json]
# flatten the list
sales_plan_details_list = [item for sublist in sales_plan_details_nested_list for item in sublist]
# pretty print the list now
print(json.dumps(sales_plan_details_list, indent=True))
答案 1 :(得分:1)
使用json.loads
或ast.literal_eval
将string
转换为list of dicts
:
import ast, json
df = pd.DataFrame(rows)
df['Sales_Plan_Details'] = df['Sales_Plan_Details'].apply(json.loads)
#alternative solution
#df['Sales_Plan_Details'] = df['Sales_Plan_Details'].apply(ast.literal_eval)
j = df.to_json(orient='records')
print (j)
[{"Sales_Plan_Details":[{"Month":"2019-1","Quantity":10,"Product_Gid":3}],
"customer_name":"ABI2","employee_name":"ASU2","location_name":"Cherai2"},
{"Sales_Plan_Details":[{"Month":"2019-1","Quantity":10,"Product_Gid":3}],
"customer_name":"ABI","employee_name":"ASU","location_name":"Cherai"}]
设置:
rows= [{
"customer_name": "ABI2",
"location_name": "Cherai2",
"employee_name": "ASU2",
"Sales_Plan_Details": "[{\"Month\": \"2019-1\", \"Quantity\": 10, \"Product_Gid\": 3}]"
},
{
"customer_name": "ABI",
"location_name": "Cherai",
"employee_name": "ASU",
"Sales_Plan_Details": "[{\"Month\": \"2019-1\", \"Quantity\": 10, \"Product_Gid\": 3}]"
}]