【问题标题】:Read a dictionary from file and convert it to python data type dict [closed]从文件中读取字典并将其转换为 python 数据类型 dict [关闭]
【发布时间】:2018-12-04 16:32:28
【问题描述】:

文件包含以下数据:

{ "_id" : ObjectId("5c04cc50792d7153282a0874"), "Name" : "Nimish", "Marks" : "100" }
{ "_id" : ObjectId("5c04cc61792d7153282a0875"), "Name" : "Ayush", "Marks" : "78" }

我需要将这些数据转换为字典列表。 已尝试ast.literal_eval(),但它会生成malformed node or string 错误。

【问题讨论】:

标签: python dictionary


【解决方案1】:

你需要在ObjectId("xxxxxx")的前后加上',然后转换成字典。 示例代码是

import json
from pprint import pprint
import ast

with open('data2.txt') as f:
    data = f.read().replace("ObjectId(", "'ObjectId(").replace(")", ")'").replace("\n", ",");

listDict = ast.literal_eval(data)
print(listDict)

输出是

({'_id': 'ObjectId("5c04cc50792d7153282a0874")', 'Name': 'Nimish', 'Marks': '100'}, {'_id': 'ObjectId("5c04cc61792d7153282a0875")', 'Name': 'Ayush', 'Marks': '78'})

【讨论】:

    【解决方案2】:

    您可以使用正则表达式替换 ObjectId 模式,然后json.loads() 会将其转换为字典。

    import json
    import re
    
    raw_string = '{"_id" : ObjectId("5c04cc50792d7153282a0874"), "Name" : "Nimish", "Marks" : "100" }'
    
    # Use regex to replace the ObjectId and parantheses
    parsed_data = re.sub(r'ObjectId\((.*)\)',r'\1',raw_string)
    
    dict_dump = json.loads(parsed_data)
    print(type(dict_dump))
    print(dict_dump)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多