Python 在本例中,将响应转换为json格式的最佳方法
如果您能帮助我找到将结果转换为json的最佳方法,我将不胜感激,如下所示。 我们得到的结果如下所示,我们得到了有关员工和公司的信息。结果,不知何故,我们得到了一个类似于T的枚举,但不是所有属性的枚举Python 在本例中,将响应转换为json格式的最佳方法,python,python-3.x,Python,Python 3.x,如果您能帮助我找到将结果转换为json的最佳方法,我将不胜感激,如下所示。 我们得到的结果如下所示,我们得到了有关员工和公司的信息。结果,不知何故,我们得到了一个类似于T的枚举,但不是所有属性的枚举 [ { "T.id":"Employee_11", "T.category":"Employee", "node_id":["11"] }, { "
[ {
"T.id":"Employee_11",
"T.category":"Employee",
"node_id":["11"]
},
{
"T.id":"Company_12",
"T.category":"Company",
"node_id":["12"],
"employeecount":800
},
{
"T.id":"id~Employee_11_to_Company_12",
"T.category":"WorksIn",
},
{
"T.id":"Employee_13",
"T.category":"Employee",
"node_id":["13"]
},
{
"T.id":"Parent_Company_14",
"T.category":"ParentCompany",
"node_id":["14"],
"employeecount":900,
"childcompany":"Company_12"
},
{
"T.id":"id~Employee_13_to_Parent_Company_14",
"T.category":"Contractorin",
}]
我们需要根据类别将此结果转换为不同的结构和分组,如果类别位于Employee、Company和ParentCompany中,那么它应该位于node_properties对象下,否则应该位于edge_properties中。此外,除了公共属性(property_id、property_category和node)之外,如果类别是公司和母公司,则要添加不同的属性。还有一些逻辑,我们必须根据“to”获取边缘对象的from和to属性。预期的反应是
"node_properties":[
{
"property_id":"Employee_11",
"property_category":"Employee",
"node":{node_id: "11"}
},
{
"property_id":"Company_12",
"property_category":"Company",
"node":{node_id: "12"},
"employeecount":800
},
{
"property_id":"Employee_13",
"property_category":"Employee",
"node":{node_id: "13"}
},
{
"property_id":"Company_14",
"property_category":"ParentCompany",
"node":{node_id: "14"},
"employeecount":900,
"childcompany":"Company_12"
}
],
"edge_properties":[
{
"from":"Employee_11",
"to":"Company_12",
"property_id":"Employee_11_to_Company_12",
},
{
"from":"Employee_13",
"to":"Parent_Company_14",
"property_id":"Employee_13_to_Parent_Company_14",
}
]
在java中,我们使用了增强的for循环、switch等。我们如何在python中编写代码,从初始结果结构获得如上所述的结构。(我是python新手),提前谢谢你
关于这里有一个我很快制定的方法,您可以根据自己的要求进行调整。您可以使用regex或您自己的函数获取
edge\u属性的ID
,然后像我那样将其分配给对象。我不太确定你的全部要求,但如果你给出的清单是所有类别,那么这就足够了
def transform(input_list):
node_properties = []
edge_properties = []
for input_obj in input_list:
# print(obj)
new_obj = {}
if input_obj['T.category'] == 'Employee' or input_obj['T.category'] == 'Company' or input_obj['T.category'] == 'ParentCompany':
new_obj['property_id'] = input_obj['T.id']
new_obj['property_category'] = input_obj['T.category']
new_obj['node'] = {input_obj['node_id'][0]}
if "employeecount" in input_obj:
new_obj['employeecount'] = input_obj['employeecount']
if "childcompany" in input_obj:
new_obj['childcompany'] = input_obj['childcompany']
node_properties.append(new_obj)
else: # You can do elif == to as well based on your requirements if there are other outliers
# You can use regex or whichever method here to split the string and add the values like above
edge_properties.append(new_obj)
return [node_properties, edge_properties]
您在python中尝试了什么?这里没有问题要解决。你能提供我们如何从结果中获得json响应的代码吗?如果你付钱给我,我很乐意给你代码。请阅读道歉,同意,我正在寻找实现这一点的最佳方法,而不是完整的代码。如果您像在Java中那样尝试自己做这件事,那将非常好。如果出现任何问题,请就此提出具体的问题。谢谢您的指导,我会检查