1

I have a string, which I retrieved as a nested JSON field from a Mongo database

"[{'actionId': '29df54c0-9f08-4231-8eb2-ca2457003f2d', 'actionName': 'Create a team', 'userActionStatus': 'COMPLETED', 'currentCount': 1, 'targetCount': 1, 'lastActionDate': datetime.datetime(2022, 6, 24, 14, 17, 17, 785000)}]"

I'm unable to parse the json with json.loads, as it's throwing a Expected value at column... error. Which is caused by the datetime.datatime object

Any ideas on how to parse this?

Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
James Lee
  • 25
  • 1
  • 5
  • It's not valid JSON because it contains a *datetime.datetime* object, which is not a valid JSON data type, so you have convert that first. – Daniel Hao Feb 27 '23 at 18:37
  • 1
    https://stackoverflow.com/questions/53596070/mongodb-pymongo-python-time-getting-the-datetime-as-string – Chris Feb 27 '23 at 18:39
  • That's not valid JSON - not just because of the `datetime.datetime` object (which is neither a string nor a numeric/Boolean/null value), but also because you have to enclose string in double quites like `"..."`, not single quotes `'...'` as you have. Anyway, you can parse this with [`eval`](https://docs.python.org/3/library/functions.html#eval), but it's [**not** considered safe](https://stackoverflow.com/q/1933451/6146136) – Driftr95 Feb 27 '23 at 18:52
  • Have a look at: [Way to use ast.literal_eval() to convert string into a datetime?](https://stackoverflow.com/questions/4235606/way-to-use-ast-literal-eval-to-convert-string-into-a-datetime/4235622#4235622) – Maurice Meyer Feb 27 '23 at 18:55

2 Answers2

0
"[{'actionId': '29df54c0-9f08-4231-8eb2-ca2457003f2d', 'actionName': 'Create a team', 'userActionStatus': 'COMPLETED', 'currentCount': 1, 'targetCount': 1, 'lastActionDate': datetime.datetime(2022, 6, 24, 14, 17, 17, 785000)}]"

This is not legal JSON, observe that single quotes are used, whilst RFC7159 stipulates double quotes ("), also datetime.datetime is not valid literal under rules shown in linked document.

You apparently got representation of python structure or in other words saved result of printing structure rather than structure itself. Adjust your code so you are able to access structure.

Daweo
  • 31,313
  • 3
  • 12
  • 25
0

Only if you trust the string returned by Mongo, you can use eval:

import datetime

s = "[{'actionId': '29df54c0-9f08-4231-8eb2-ca2457003f2d', 'actionName': 'Create a team', 'userActionStatus': 'COMPLETED', 'currentCount': 1, 'targetCount': 1, 'lastActionDate': datetime.datetime(2022, 6, 24, 14, 17, 17, 785000)}]"

out = eval(s)

Output:

>>> out
[{'actionId': '29df54c0-9f08-4231-8eb2-ca2457003f2d',
  'actionName': 'Create a team',
  'userActionStatus': 'COMPLETED',
  'currentCount': 1,
  'targetCount': 1,
  'lastActionDate': datetime.datetime(2022, 6, 24, 14, 17, 17, 785000)}]
Corralien
  • 109,409
  • 8
  • 28
  • 52