pandas python Dataframe 转换器到json和更多信息

xytpbqjk  于 2022-12-28  发布在  Python
关注(0)|答案(1)|浏览(87)

请帮助我解决我的问题...我正在尝试转换我的 Dataframe 到json和添加外部json。

technologies = {
    'rid':[1000208,1000209,11111],
    'num' :[1,2,3],
    'cid':[10002,10003,10000]
              }
df = pd.DataFrame(technologies)
print(df)
json_res=df.to_json(orient="records")
print(json_res)

[{“编号”:1000208,“编号”:1,“代码”:10002},{“编号”:1000209,“编号”:2,“代码”:10003},{“编号”:11111,“编号”:3,“代码”:10000}]
...只想添加关键字key_word =“report_result”预期结果[{“report_result”:[{“编号”:1000208,“编号”:1,“代码”:10002},{“编号”:1000209,“编号”:2,“代码”:10003},{“编号”:11111,“编号”:3,“代码”:10000}]

yqlxgs2m

yqlxgs2m1#

要将外部JSON对象添加到 Dataframe 的JSON表示中,可以使用json.dumps函数并将df.to_json(orient="records")的结果作为输入传递。

import json

# Convert the dataframe to JSON
json_res = df.to_json(orient="records")

# Add an outer JSON object
outer_json = {"report_result": json.loads(json_res)}

# Convert the outer JSON object to a string
json_string = json.dumps([outer_json])
json_obj = json.loads(json_string)

print(json_obj)

产出将是:

[{"report_result": [{"rid": 1000208, "num": 1, "cid": 10002}, {"rid": 1000209, "num": 2, "cid": 10003}, {"rid": 11111, "num": 3, "cid": 10000}]}]

相关问题