How to get string objects instead of Unicode from JSON?

前端 未结 21 915
伪装坚强ぢ
伪装坚强ぢ 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:21

    I ran into this problem too, and having to deal with JSON, I came up with a small loop that converts the unicode keys to strings. (simplejson on GAE does not return string keys.)

    obj is the object decoded from JSON:

    if NAME_CLASS_MAP.has_key(cls):
        kwargs = {}
        for i in obj.keys():
            kwargs[str(i)] = obj[i]
        o = NAME_CLASS_MAP[cls](**kwargs)
        o.save()
    

    kwargs is what I pass to the constructor of the GAE application (which does not like unicode keys in **kwargs)

    Not as robust as the solution from Wells, but much smaller.

提交回复
热议问题