python - 如何将包含 '_' 的 JSON 字段拆分为子对象?

标签 python json

我有以下 JSON 对象,我需要在其中后处理一些标签:

{
 'id': '123',
 'type': 'A',
 'fields': 
  {
      'device_safety': 
      {
         'cost': 0.237,
         'total': 22
      },
      'device_unit_replacement': 
      {
         'cost': 0.262,
         'total': 7
      },
      'software_generalinfo': 
      {
         'cost': 3.6,
         'total': 10
      }
  }
}

我需要按 _ 拆分标签名称以获得以下层次结构:

{
 'id': '123',
 'type': 'A',
 'fields': 
  {
      'device': 
      {
         'safety': 
         {
             'cost': 0.237,
             'total': 22
         },
         'unit':
         {
             'replacement':
             {
                  'cost': 0.262,
                  'total': 7
             }  
         }
      },
      'software': 
      {
         'generalinfo':
         {
            'cost': 3.6,
            'total': 10
         }
      }
  }
}

这是我当前的版本,但我陷入困境,不知道如何处理字段的层次结构:

import json

json_object = json.load(raw_json)

newjson = {}
for x, y in json_object['fields'].items():
    hierarchy = y.split("_")
    if len(hierarchy) > 1:
         for k in hierarchy:
              newjson[k] = ????

newjson = json.dumps(newjson, indent = 4)

最佳答案

这是一个递归函数,它将处理dict并分割键:

def splitkeys(dct):
    if not isinstance(dct, dict):
        return dct
    new_dct = {}
    for k, v in dct.items():
        bits = k.split('_')
        d = new_dct
        for bit in bits[:-1]:
            d = d.setdefault(bit, {})
        d[bits[-1]] = splitkeys(v)
    return new_dct


>>> splitkeys(json_object)
{'fields': {'device': {'safety': {'cost': 0.237, 'total': 22},
                       'unit': {'replacement': {'cost': 0.262, 'total': 7}}},
            'software': {'generalinfo': {'cost': 3.6, 'total': 10}}},
 'id': '123',
 'type': 'A'}

关于python - 如何将包含 '_' 的 JSON 字段拆分为子对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64467452/

相关文章:

javascript - 在异步 XMLHttpRequest 的数据可用后执行代码

javascript - 将 JSON 转换为 Javascript 数组

python - youtube api v3 返回的结果少于实体

python - 如何在 OSX Lion 上的 Eclipse 中配置 PyDev 以使用 32 位 Python 解释器

python - 在 python 中用空格重新拆分

php - $.each 除 firefox 3.6 外不工作

带有 key :object 的 JavaScript json

python - python pandas 重组索引中的内存泄漏

python - 尝试遍历嵌套的 xml 标签,但递归函数未完全深度遍历

json - Postgres 对 json 字段的全文搜索