skip to Main Content

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?

2

Answers


  1. "[{'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.

    Login or Signup to reply.
  2. 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)}]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search