如何将特定数组/列表转换为 json 结构中的字典
python 440
原文标题 :how to convert a particular array/list to a dictionary in a json structure
我有以下json:
[
{
"id": 1,
"object_k_id": "",
"object_type": "schema",
"object_meta": [
{
"source_id": 0,
"database": "rawdwh",
"schema": "abc"
}
],
"description": "A schema of all customer data",
"business_name": "",
"business_logic": "",
"owners": [
"xyz@gmail.com"
],
"stewards": [
"xyz@gmail.com"
],
"verified_use_cases": "",
"classifications": [],
"domains": ""
}
]
如何仅删除 object_meta 的 [] 因为我希望它作为字典而不是包含字典的数组。通过执行以下操作,我从 Dataframe 获得了上述 json
def convert_to_json(item,df,final_columnnames,dict_meta):
meta_obj = df.groupby(['id']).apply(lambda x: x[dict_meta.get(item)].to_dict('records')).reset_index().rename(columns={0:'object_meta'})
meta_obj_json = pandas.merge(df,meta_obj,how='inner',on='id')
result_json=meta_obj_json[final_columnnames].to_json(orient='records')
#print(type(result_json))
final_json=json.dumps(json.loads(result_json), indent=3, sort_keys=False)
上面的代码所做的是将特定的 Dataframe 转换为 json 格式,其中 object_meta 列是一个超结构,就像一个 dict 值的字典,但是 object_meta 又是 list 类型,但我希望它只是一个 dict dict如下图
{
"id": 1,
"object_k_id": "",
"object_type": "schema",
"object_meta":
{
"source_id": 0,
"database": "raw data",
"schema": "abc"
}
,
"description": "A schema of all customer data",
"business_name": "",
"business_logic": "",
"owners": [
""
],
"stewards": [
"xyz@gmail.com"
],
"verified_use_cases": "",
"classifications": [],
"domains": ""
}
]
请帮忙。
提前致谢