为了账号安全,请及时绑定邮箱和手机立即绑定

如何将包含“_”的 JSON 字段拆分为子对象?

如何将包含“_”的 JSON 字段拆分为子对象?

www说 2023-12-20 16:19:43
我有以下 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 jsonjson_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)
查看完整描述

1 回答

?
白板的微信

TA贡献1883条经验 获得超3个赞

这是处理 adict并拆分键的递归函数:


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'}


查看完整回答
反对 回复 2023-12-20
  • 1 回答
  • 0 关注
  • 47 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信