How to get string objects instead of Unicode from JSON?

前端 未结 21 1086
伪装坚强ぢ
伪装坚强ぢ 2020-11-22 14:43

I\'m using Python 2 to parse JSON from ASCII encoded text files.

When loading these files with either json or simplejson, all my

21条回答
  •  一整个雨季
    2020-11-22 15:18

    There exists an easy work-around.

    TL;DR - Use ast.literal_eval() instead of json.loads(). Both ast and json are in the standard library.

    While not a 'perfect' answer, it gets one pretty far if your plan is to ignore Unicode altogether. In Python 2.7

    import json, ast
    d = { 'field' : 'value' }
    print "JSON Fail: ", json.loads(json.dumps(d))
    print "AST Win:", ast.literal_eval(json.dumps(d))
    

    gives:

    JSON Fail:  {u'field': u'value'}
    AST Win: {'field': 'value'}
    

    This gets more hairy when some objects are really Unicode strings. The full answer gets hairy quickly.

提交回复
热议问题