栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用字典和数组将点符号字符串转换为嵌套的Python对象

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用字典和数组将点符号字符串转换为嵌套的Python对象

因此,我不确定此解决方案是否有任何警告,但这似乎适用于我抛出的一些用例:

import json, redef build_job():    def branch(tree, vector, value):        # Originally based on https://stackoverflow.com/a/47276490/2903486        # Convert Boolean        if isinstance(value, str): value = value.strip() if value.lower() in ['true', 'false']:     value = True if value.lower() == "true" else False        # Convert JSON        try: value = json.loads(value)        except: pass        key = vector[0]        arr = re.search('[([0-9]+)]', key)        if arr: # Get the index of the array, and remove it from the key name arr = arr.group(0) key = key.replace(arr,'') arr = int(arr.replace('[','').replace(']','')) if key not in tree:     # If we dont have an array already, turn the dict from the previous      # recursion into an array and append to it     tree[key] = []     tree[key].append(value          if len(vector) == 1          else branch({} if key in tree else {},          vector[1:],          value)) else:     # Check to see if we are inside of an existing array here     isInArray = False     for i in range(len(tree[key])):         if tree[key][i].get(vector[1:][0], False):  isInArray = tree[key][i][vector[1:][0]]     if isInArray and arr < len(tree[key])         and isinstance(tree[key][arr], list):         # Respond accordingly by appending or updating the value         tree[key][arr].append(value   if len(vector) == 1   else branch(tree[key] if key in tree else {},   vector[1:],   value))     else:         # Make sure we have an index to attach the requested array to         while arr >= len(tree[key]):  tree[key].append({})         # update the existing array with a dict         tree[key][arr].update(value   if len(vector) == 1   else branch(tree[key][arr] if key in tree else {},   vector[1:],   value)) # Turn comma deliminated values to lists if len(vector) == 1 and len(tree[key]) == 1:     tree[key] = value.split(",")        else: # Add dictionaries together tree.update({key: value      if len(vector) == 1      else branch(tree[key] if key in tree else {},      vector[1:],      value)})        return tree    file = [{        "one.array[0].dict.dont-worry-about-me": "some value",        "one.array[0].dict.arrOne[0]": "1,2,3",        "one.array[0].dict.arrTwo[1]": "4,5,6",        "one.array[1].x.y[0].z[0].id": "789"    }]    rowList = []    for row in file:        rowObj = {}        for colName, rowValue in row.items(): rowObj.update(branch(rowObj, colName.split("."), rowValue))        rowList.append(rowObj)    return rowListprint(json.dumps(build_job(), indent=4))

结果:

[    {        "one": { "array": [     {         "dict": {  "dont-worry-about-me": "some value",  "arrOne": [      "1",      "2",      "3"  ],  "arrTwo": [      "4",      "5",      "6"  ]         }     },     {         "x": {  "y": [      {          "z": [   {       "id": 789   }          ]      }  ]         }     } ]        }    }]


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/646215.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号