-1

File contains the following data:

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

I need these data to be converted to list of dictionaries. Have tried ast.literal_eval() but it generates malformed node or string error.

Dadep
  • 2,796
  • 5
  • 27
  • 40
  • what is `ObjectId("5c04cc50792d7153282a0874")` there ? – Mehrdad Pedramfar Dec 04 '18 at 07:42
  • @mehrdad-pedramfar I think it's unique ID created by MongoDB for each record. – Sociopath Dec 04 '18 at 07:47
  • 1
    Possible duplicate of [Malformed String ValueError ast.literal\_eval() with String representation of Tuple](https://stackoverflow.com/questions/14611352/malformed-string-valueerror-ast-literal-eval-with-string-representation-of-tup) – alseether Dec 04 '18 at 07:50

2 Answers2

1

You need to add ' before and after of ObjectId("xxxxxx"), then convert to dictionary. sample code is

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)

output is

({'_id': 'ObjectId("5c04cc50792d7153282a0874")', 'Name': 'Nimish', 'Marks': '100'}, {'_id': 'ObjectId("5c04cc61792d7153282a0875")', 'Name': 'Ayush', 'Marks': '78'})
Prince Francis
  • 2,995
  • 1
  • 14
  • 22
1

You can use regex to replace the ObjectId pattern, then json.loads() will convert it to dictionary.

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)
Arvind
  • 1,006
  • 10
  • 16