【问题标题】:Insert element in Nested Json using another dict python使用另一个字典 python 在嵌套 Json 中插入元素
【发布时间】:2020-01-01 14:13:43
【问题描述】:

我有如下的 json 对象和映射器,

Json 对象:

{
    'App Builder': {
        'ID': '1',
        'children': [{
            'API Builder': {
                'ID': '2'
            }
        }, {
            'UI': {
                'ID': '3',
                'children': [{
                    'UI Builder': {
                        'ID': '4'
                    }
                }, {
                    'Template': {
                        'ID': '5',
                        'children': [{
                            'Angular': {
                                'ID': '6'
                            }
                        }, {
                            'React': {
                                'ID': '7'
                            }
                        }, {
                            'PHP': {
                                'ID': '8'
                            }
                        }]
                    }
                }]
            }
        }]
    }
}

映射器:

{
    '1': ['create an app', 'create app for me', 'can you create an application?'],
    '2': ['create an app using API Buider', 'make an application using API Builder', 'create API Builder application'],
    '3': ['create an app using user interface', 'make an application using UI', 'create UI application'],
    '4': ['create an app using UI Buider', 'make an application using UI Builder', 'create UI Builder application'],
    '5': ['create an app using Template', 'make an application using Template', 'create Template application'],
    '6': ['create an app using Angular', 'make an application using Angular template', 'create Angular application'],
    '7': ['create an app using React', 'make an application using React template', 'create React application'],
    '8': ['create an app using PHP', 'make an application using PHP template', 'create PHP application']
}

两个对象都包含“ID”,我需要在原始 json 对象中附加值,如下所示,

{
    "App Builder": {
        "ID": "1",
        "1": ["create an app", "create app for me", "can you create an application?"],

        "children": [{
            "API Builder": {
                "ID": "2",
                "2": ["create an app using API Buider", "make an application using API Builder", "create API Builder application"]

            }
        }, {
            "UI": {
                "ID": "3",
                "3": ["create an app using user interface", "make an application using UI", "create UI application"],

                "children": [{
                    "UI Builder": {
                        "ID": "4",
                        "4": ["create an app using UI Buider", "make an application using UI Builder", "create UI Builder application"]

                    }
                }, {
                    "Template": {
                        "ID": "5",
                        "5": ["create an app using Template", "make an application using Template", "create Template application"],
                        "children": [{
                            "Angular": {
                                "ID": "6",
                                "6": ["create an app using Angular", "make an application using Angular template", "create Angular application"]

                            }
                        }, {
                            "React": {
                                "ID": "7",
                                "7": ["create an app using React", "make an application using React template", "create React application"]

                            }
                        }, {
                            "PHP": {
                                "ID": "8",
                                "8": ["create an app using PHP", "make an application using PHP template", "create PHP application"]

                            }
                        }]
                    }
                }]
            }
        }]
    }
}

我尝试使用下面的方法获取所需 json 对象的路径。

json_path = {}
for intent in all_walks:
    ep = []
    temp = s
    i=0
    for val in intent.split('/'):
        if i==0:
            ep.append(val)
            temp = temp[val]
        else:
            temp = temp['children']
            ep.append('children')
            for item in temp:
                if val in item.keys():
                    ep.append(val)
                    temp = item[val]
        i+=1
        json_path[intent] = ep

print(json_path)

它给了我,

{'App Builder': ['App Builder'], 'App Builder/API Builder': ['App Builder', 'children', 'API Builder'], 'App Builder/UI': ['App Builder', 'children', 'UI'], 'App Builder/UI/UI Builder': ['App Builder', 'children', 'UI', 'children', 'UI Builder'], 'App Builder/UI/Template': ['App Builder', 'children', 'UI', 'children', 'Template'], 'App Builder/UI/Template/Angular': ['App Builder', 'children', 'UI', 'children', 'Template', 'children', 'Angular'], 'App Builder/UI/Template/React': ['App Builder', 'children', 'UI', 'children', 'Template', 'children', 'React'], 'App Builder/UI/Template/PHP': ['App Builder', 'children', 'UI', 'children', 'Template', 'children', 'PHP']}

我再次不能使用它,因为children 是一个数组。

如何解决这个问题。

任何帮助都将是可观的。

【问题讨论】:

    标签: python json python-3.x python-2.7 nested


    【解决方案1】:

    您可以使用json.loadsobject_hook 参数,这是一个可选函数,将使用解码的任何对象文字(一个字典)的结果来调用。例如,

    对于下面的 JSON

    sample_json = """{
        "App Builder": {
            "ID": "1",
            "children": [
                {
                    "API Builder": {
                        "ID": "2"
                    }
                },
                {
                    "UI": {
                        "ID": "3",
                        "children": [
                            {
                                "UI Builder": {
                                    "ID": "4"
                                }
                            },
                            {
                                "Template": {
                                    "ID": "5",
                                    "children": [
                                        {
                                            "Angular": {
                                                "ID": "6"
                                            }
                                        },
                                        {
                                            "React": {
                                                "ID": "7"
                                            }
                                        },
                                        {
                                            "PHP": {
                                                "ID": "8"
                                            }
                                        }
                                    ]
                                }
                            }
                        ]
                    }
                }
            ]
        }
    }"""
    

    并使用以下映射器,

    mapper = {
        '1': ['create an app', 'create app for me', 'can you create an application?'],
        '2': ['create an app using API Buider', 'make an application using API Builder', 'create API Builder application'],
        '3': ['create an app using user interface', 'make an application using UI', 'create UI application'],
        '4': ['create an app using UI Buider', 'make an application using UI Builder', 'create UI Builder application'],
        '5': ['create an app using Template', 'make an application using Template', 'create Template application'],
        '6': ['create an app using Angular', 'make an application using Angular template', 'create Angular application'],
        '7': ['create an app using React', 'make an application using React template', 'create React application'],
        '8': ['create an app using PHP', 'make an application using PHP template', 'create PHP application']
    }
    

    你可以像下面这样实现object_hook函数

    import json
    
    def hook(obj):
        if 'ID' in obj:
            key = obj["ID"]
            obj.update({key: mapper[key]})
        return obj
    
    data = json.loads(sample_json, object_hook=hook)
    json = json.dumps(data, indent=4)
    print(json)
    

    将产生以下输出

    {
        "App Builder": {
            "ID": "1",
            "children": [
                {
                    "API Builder": {
                        "ID": "2",
                        "2": [
                            "create an app using API Buider",
                            "make an application using API Builder",
                            "create API Builder application"
                        ]
                    }
                },
                {
                    "UI": {
                        "ID": "3",
                        "children": [
                            {
                                "UI Builder": {
                                    "ID": "4",
                                    "4": [
                                        "create an app using UI Buider",
                                        "make an application using UI Builder",
                                        "create UI Builder application"
                                    ]
                                }
                            },
                            {
                                "Template": {
                                    "ID": "5",
                                    "children": [
                                        {
                                            "Angular": {
                                                "ID": "6",
                                                "6": [
                                                    "create an app using Angular",
                                                    "make an application using Angular template",
                                                    "create Angular application"
                                                ]
                                            }
                                        },
                                        {
                                            "React": {
                                                "ID": "7",
                                                "7": [
                                                    "create an app using React",
                                                    "make an application using React template",
                                                    "create React application"
                                                ]
                                            }
                                        },
                                        {
                                            "PHP": {
                                                "ID": "8",
                                                "8": [
                                                    "create an app using PHP",
                                                    "make an application using PHP template",
                                                    "create PHP application"
                                                ]
                                            }
                                        }
                                    ],
                                    "5": [
                                        "create an app using Template",
                                        "make an application using Template",
                                        "create Template application"
                                    ]
                                }
                            }
                        ],
                        "3": [
                            "create an app using user interface",
                            "make an application using UI",
                            "create UI application"
                        ]
                    }
                }
            ],
            "1": [
                "create an app",
                "create app for me",
                "can you create an application?"
            ]
        }
    }
    

    【讨论】:

      【解决方案2】:

      我做了一个递归函数来设置映射数据:

      data = {
          'App Builder': {
              'ID': '1',
              'children': [{
                  'API Builder': {
                      'ID': '2'
                  }
              }, {
                  'UI': {
                      'ID': '3',
                      'children': [{
                          'UI Builder': {
                              'ID': '4'
                          }
                      }, {
                          'Template': {
                              'ID': '5',
                              'children': [{
                                  'Angular': {
                                      'ID': '6'
                                  }
                              }, {
                                  'React': {
                                      'ID': '7'
                                  }
                              }, {
                                  'PHP': {
                                      'ID': '8'
                                  }
                              }]
                          }
                      }]
                  }
              }]
          }
      }
      
      mapper = {
          '1': ['create an app', 'create app for me', 'can you create an application?'],
          '2': ['create an app using API Buider', 'make an application using API Builder', 'create API Builder application'],
          '3': ['create an app using user interface', 'make an application using UI', 'create UI application'],
          '4': ['create an app using UI Buider', 'make an application using UI Builder', 'create UI Builder application'],
          '5': ['create an app using Template', 'make an application using Template', 'create Template application'],
          '6': ['create an app using Angular', 'make an application using Angular template', 'create Angular application'],
          '7': ['create an app using React', 'make an application using React template', 'create React application'],
          '8': ['create an app using PHP', 'make an application using PHP template', 'create PHP application']
      }
      
      def setDataFromNestedDict(data, dictKey):
          if isinstance(data, dict):
              if dictKey in data.keys():
                  data[data[dictKey]] = mapper[data[dictKey]]
              for key, value in data.items():
                  if isinstance(value, dict):
                      setDataFromNestedDict(value, dictKey)
                  elif isinstance(value, list):
                      for item in value:
                          setDataFromNestedDict(item,dictKey)
      
          elif isinstance(data, list):
              for item in data:
                  setDataFromNestedDict(item,dictKey)
      
      setDataFromNestedDict(data, 'ID')
      print(data)
      

      输出:

      {'App Builder': {'1': ['create an app',
         'create app for me',
         'can you create an application?'],
        'ID': '1',
        'children': [{'API Builder': {'2': ['create an app using API Buider',
            'make an application using API Builder',
            'create API Builder application'],
           'ID': '2'}},
         {'UI': {'3': ['create an app using user interface',
            'make an application using UI',
            'create UI application'],
           'ID': '3',
           'children': [{'UI Builder': {'4': ['create an app using UI Buider',
               'make an application using UI Builder',
               'create UI Builder application'],
              'ID': '4'}},
            {'Template': {'5': ['create an app using Template',
               'make an application using Template',
               'create Template application'],
              'ID': '5',
              'children': [{'Angular': {'6': ['create an app using Angular',
                  'make an application using Angular template',
                  'create Angular application'],
                 'ID': '6'}},
               {'React': {'7': ['create an app using React',
                  'make an application using React template',
                  'create React application'],
                 'ID': '7'}},
               {'PHP': {'8': ['create an app using PHP',
                  'make an application using PHP template',
                  'create PHP application'],
                 'ID': '8'}}]}}]}}]}}
      

      【讨论】:

      • def setDataFromNestedDict 这是方法,在输入输出之间观察
      【解决方案3】:

      你可以使用简单的递归:

      data = {'App Builder': {'ID': '1', 'children': [{'API Builder': {'ID': '2'}}, {'UI': {'ID': '3', 'children': [{'UI Builder': {'ID': '4'}}, {'Template': {'ID': '5', 'children': [{'Angular': {'ID': '6'}}, {'React': {'ID': '7'}}, {'PHP': {'ID': '8'}}]}}]}}]}}
      l = {'1': ['create an app', 'create app for me', 'can you create an application?'], '2': ['create an app using API Buider', 'make an application using API Builder', 'create API Builder application'], '3': ['create an app using user interface', 'make an application using UI', 'create UI application'], '4': ['create an app using UI Buider', 'make an application using UI Builder', 'create UI Builder application'], '5': ['create an app using Template', 'make an application using Template', 'create Template application'], '6': ['create an app using Angular', 'make an application using Angular template', 'create Angular application'], '7': ['create an app using React', 'make an application using React template', 'create React application'], '8': ['create an app using PHP', 'make an application using PHP template', 'create PHP application']}
      def get_vals(d):
        if 'ID' not in d:
           return {a:get_vals(b) for a, b in d.items()}
        return {**d, d['ID']:l[d['ID']], 'children':[get_vals(i) for i in d.get('children', [])]}
      

      import json
      print(json.dumps(get_vals(data), indent=4))
      

      输出:

      {
      "App Builder": {
          "ID": "1",
          "1": [
              "create an app",
              "create app for me",
              "can you create an application?"
          ],
          "children": [
              {
                  "API Builder": {
                      "ID": "2",
                      "2": [
                          "create an app using API Buider",
                          "make an application using API Builder",
                          "create API Builder application"
                      ],
                      "children": []
                  }
              },
              {
                  "UI": {
                      "ID": "3",
                      "children": [
                          {
                              "UI Builder": {
                                  "ID": "4",
                                  "4": [
                                      "create an app using UI Buider",
                                      "make an application using UI Builder",
                                      "create UI Builder application"
                                  ],
                                  "children": []
                              }
                          },
                          {
                              "Template": {
                                  "ID": "5",
                                  "children": [
                                      {
                                          "Angular": {
                                              "ID": "6",
                                              "6": [
                                                  "create an app using Angular",
                                                  "make an application using Angular template",
                                                  "create Angular application"
                                              ],
                                              "children": []
                                          }
                                      },
                                      {
                                          "React": {
                                              "ID": "7",
                                              "7": [
                                                  "create an app using React",
                                                  "make an application using React template",
                                                  "create React application"
                                              ],
                                              "children": []
                                          }
                                      },
                                      {
                                          "PHP": {
                                              "ID": "8",
                                              "8": [
                                                  "create an app using PHP",
                                                  "make an application using PHP template",
                                                  "create PHP application"
                                              ],
                                              "children": []
                                          }
                                      }
                                  ],
                                  "5": [
                                      "create an app using Template",
                                      "make an application using Template",
                                      "create Template application"
                                  ]
                              }
                          }
                      ],
                      "3": [
                          "create an app using user interface",
                          "make an application using UI",
                          "create UI application"
                      ]
                  }
              }
          ],
      }
      

      【讨论】:

        【解决方案4】:

        我的同事@Akshay pai 提出了另一个令人印象深刻的解决方案。其背后的想法是通过递归调用使用引用调用。

        def restructure(tree_data):
            if tree_data is None:
                return tree_data
            root_element = list(tree_data.keys())[0]
            tree_data = tree_data[root_element]
            tree_data["utterance"] = intent_mapper[tree_data["ID"]]
            if "children" not in tree_data:
                return tree_data
            for child in tree_data["children"]:
                restructure(child)
        restructure(tree_data)
        

        O/P:

        {
            "App Builder": {
                "ID": "1",
                "children": [
                    {
                        "API Builder": {
                            "ID": "2",
                            "utterance": [
                                "create an app using API Buider",
                                "make an application using API Builder",
                                "create API Builder application"
                            ]
                        }
                    },
                    {
                        "UI": {
                            "ID": "3",
                            "children": [
                                {
                                    "UI Builder": {
                                        "ID": "4",
                                        "utterance": [
                                            "create an app using UI Buider",
                                            "make an application using UI Builder",
                                            "create UI Builder application"
                                        ]
                                    }
                                },
                                {
                                    "Template": {
                                        "ID": "5",
                                        "children": [
                                            {
                                                "Angular": {
                                                    "ID": "6",
                                                    "utterance": [
                                                        "create an app using Angular",
                                                        "make an application using Angular template",
                                                        "create Angular application"
                                                    ]
                                                }
                                            },
                                            {
                                                "React": {
                                                    "ID": "7",
                                                    "utterance": [
                                                        "create an app using React",
                                                        "make an application using React template",
                                                        "create React application"
                                                    ]
                                                }
                                            },
                                            {
                                                "PHP": {
                                                    "ID": "8",
                                                    "utterance": [
                                                        "create an app using PHP",
                                                        "make an application using PHP template",
                                                        "create PHP application"
                                                    ]
                                                }
                                            }
                                        ],
                                        "utterance": [
                                            "create an app using Template",
                                            "make an application using Template",
                                            "create Template application"
                                        ]
                                    }
                                }
                            ],
                            "utterance": [
                                "create an app using user interface",
                                "make an application using UI",
                                "create UI application"
                            ]
                        }
                    }
                ],
                "utterance": [
                    "create an app",
                    "create app for me",
                    "can you create an application?"
                ]
            }
        }
        

        【讨论】:

          猜你喜欢
          • 2017-11-24
          • 2020-03-04
          • 1970-01-01
          • 1970-01-01
          • 2018-05-31
          • 2018-11-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多