我想使用python中的特定键值将示例JSON数据转换为嵌套JSON [英] i want to convert sample JSON data into nested JSON using specific key-value in python

查看:73
本文介绍了我想使用python中的特定键值将示例JSON数据转换为嵌套JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我下面有JSON格式的示例数据:

I have below sample data in JSON format :

project_cost_details是查询后的数据库结果集.

project_cost_details is my database result set after querying.

{
    "1": {
        "amount": 0,
        "breakdown": [
            {
                "amount": 169857,
                "id": 4,
                "name": "SampleData",
                "parent_id": "1"
            }
          ],
         "id": 1,
        "name": "ABC PR"
    }
}

这里是完整的json: https://jsoneditoronline.org/?id=2ce7ab19af6f420397b07b939674f49c

Here is full json : https://jsoneditoronline.org/?id=2ce7ab19af6f420397b07b939674f49c

预期输出: https://jsoneditoronline.org/?id=56a47e6f8e424fe8ac58c5e0732168d7

我有这个示例JSON,它是使用代码循环创建的.但我一直坚持如何将其转换为预期的JSON格式.我正在进行顺序更改,需要转换为树状或嵌套JSON格式.

I have this sample JSON which i created using loops in code. But i am stuck at how to convert this to expected JSON format. I am getting sequential changes, need to convert to tree like or nested JSON format.

在Python中尝试:

Trying in Python :


project_cost = {}
        for cost in project_cost_details:
            if cost.get('Parent_Cost_Type_ID'):
                project_id = str(cost.get('Project_ID'))
                parent_cost_type_id = str(cost.get('Parent_Cost_Type_ID'))
                if project_id not in project_cost:
                    project_cost[project_id] = {}
                if "breakdown" not in project_cost[project_id]:
                    project_cost[project_id]["breakdown"] = []
                if 'amount' not in project_cost[project_id]:
                    project_cost[project_id]['amount'] = 0
                project_cost[project_id]['name'] = cost.get('Title')
                project_cost[project_id]['id'] = cost.get('Project_ID')
                if parent_cost_type_id == cost.get('Cost_Type_ID'):
                    project_cost[project_id]['amount'] += int(cost.get('Amount'))
                #if parent_cost_type_id is None:

                project_cost[project_id]["breakdown"].append(
                    {
                        'amount': int(cost.get('Amount')),
                        'name': cost.get('Name'),
                        'parent_id': parent_cost_type_id,
                        'id' : cost.get('Cost_Type_ID')
                    }
                )

由此我得到示例JSON.如果仅以所需的格式获得此代码,那将是很好的.

from this i am getting sample JSON. It will be good if get in this code only desired format.

也尝试在此提及此解决方案:

Also tried this solution mention here : https://adiyatmubarak.wordpress.com/2015/10/05/group-list-of-dictionary-data-by-particular-key-in-python/

推荐答案

我获得了将示例JSON转换为预期JSON的方法:

I got approach to convert sample JSON to expected JSON :

data = [
 { "name" : "ABC", "parent":"DEF",  },
 { "name" : "DEF", "parent":"null" },
 { "name" : "new_name", "parent":"ABC" },
 { "name" : "new_name2", "parent":"ABC" },
 { "name" : "Foo", "parent":"DEF"},
 { "name" : "Bar", "parent":"null"},
  { "name" : "Chandani", "parent":"new_name", "relation": "rel", "depth": 3 },
  { "name" : "Chandani333", "parent":"new_name", "relation": "rel", "depth": 3 }
]

result = {x.get("name"):x for x in data}
#print(result)
tree = [];
for a in data:
    #print(a)
    if a.get("parent") in result:
        parent = result[a.get("parent")]
    else:
        parent = "" 
    if parent:
        if "children" not in parent:
            parent["children"] = []
        parent["children"].append(a)

    else:
        tree.append(a)

参考帮助: http://jsfiddle.net/9FqKS/这是我转换为Python的JavaScript解决方案

Reference help : http://jsfiddle.net/9FqKS/ this is a JavaScript solution i converted to Python

这篇关于我想使用python中的特定键值将示例JSON数据转换为嵌套JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆