Search code examples
pythonjsondatetimepython-2.7python-dateutil

How to convert json string into normal string?


I had an earlier question, which I have deleted in favour of this one. Since I was under the wrong assumption that it had something to do with the dateutil version.

test1 = dateutil.parser.parse("2013-01-24T16:50:42+00:00")  

this works fine and I get a datetime.

But

dthandler = lambda obj: obj.isoformat() if isinstance(obj, datetime.datetime) else None
test2 =  json.dumps(event.due_date_time, default=dthandler)

print test2 --> "2013-01-24T16:50:42+00:00"

This looks to me like a normal string

test3 = dateutil.parser.parse(test2)

This crashes saying ValueError: unknown string format

So how do I convert json string into 'normal' string?


Solution

  • You are forgetting that JSON puts quotes around the string. You have the following value:

    jsonvalue = '"2013-01-24T16:50:42+00:00"'
    

    Note the double quotes there.

    You'd need to load that value using the json.loads() method again, which in this case just removes the quotes again:

    >>> print json.loads(jsonvalue)
    2013-01-24T16:50:42+00:00
    

    Note that now the quotes are gone again. You could also just strip the quotes with .strip('"') if you have a mix:

    >>> print jsonvalue.strip('"')
    2013-01-24T16:50:42+00:00
    

    but since you are expecting JSON data, why not just treat it as json data and use the json module for this to turn it back to Python data.