【问题标题】:Convert dictionary with equals to json dictionary将具有等于的字典转换为 json 字典
【发布时间】:2019-09-13 07:32:49
【问题描述】:

在 Python 中,如何转换如下所示的字符串对象

"{
 apartment=false, 
 walls=[{min_height=18, max_height=3, color=WHITE}], 
 appliances=[{type=[oven, washing_machine, microwave, drying_machine, 
   dish_washer, television]}],
 rooms=[{bathroom=true, floor=2}, {bedroom=true, floor=[2,3], needs_renovation=EXCLUDE}], 
 value=[{sale_price=9003.01, occupied=true, family_unit=UNKNOWN}]
}"

像这样的字典对象?

{
 "apartment": False, 
 "walls": [{"min_height": 18, "max_height": 3, "color": "WHITE"}], 
 "appliances": [{"type": ["oven", "washing_machine", "microwave", "drying_machine", 
   "dish_washer", "television"]}],
 "rooms": [{"bathroom": True, "floor": 2}, {"bedroom": True, "floor":[2,3], "needs_renovation": "EXCLUDE"}], 
 "value": [{"sale_price": 9003.01, "occupied": True, "family_unit": "UNKNOWN"}]
}

我使用的是Simple way to convert a string to a dictionary,但它并没有让我走得更远,因为我无法处理嵌套的字典和列表。

【问题讨论】:

    标签: python json string dictionary


    【解决方案1】:

    使用正则表达式和普通字符串替换,以及 json 包:

    import json
    from pprint import pprint
    
    string = '''{
     apartment=false, 
     walls=[{min_height=18, max_height=3, color=WHITE}], 
     appliances=[{type=[oven, washing_machine, microwave, drying_machine, 
       dish_washer, television]}],
     rooms=[{bathroom=true, floor=2}, {bedroom=true, floor=[2,3], needs_renovation=EXCLUDE}], 
     value=[{sale_price=9003.01, occupied=true, family_unit=UNKNOWN}]
    }'''
    
    processed = re.sub(r'([A-Za-z_]+)', r'"\1"', string.replace('\n', '')).replace('=', ':').replace('"true"', 'true').replace('"false"', 'false')
    
    pprint(json.loads(processed))
    

    输出:

    {'apartment': False,
     'appliances': [{'type': ['oven',
                              'washing_machine',
                              'microwave',
                              'drying_machine',
                              'dish_washer',
                              'television']}],
     'rooms': [{'bathroom': True, 'floor': 2},
               {'bedroom': True, 'floor': [2, 3], 'needs_renovation': 'EXCLUDE'}],
     'value': [{'family_unit': 'UNKNOWN', 'occupied': True, 'sale_price': 9003.01}],
     'walls': [{'color': 'WHITE', 'max_height': 3, 'min_height': 18}]}
    

    【讨论】:

    • 这太好了!在我的数据中,其他字典值的可能性包括:“abc_123”、“123+”和“321-456”。如何更新正则表达式以将它们视为字符串并保留其他纯整数和浮点类型?
    • @Kevin 您可以将第一个正则表达式更改为使用 \w 并添加另一个 re.sub 调用以仅从数字中删除引号,我认为?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-04
    • 2014-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-19
    相关资源
    最近更新 更多