How to get string objects instead of Unicode from JSON?

前端 未结 21 1201
伪装坚强ぢ
伪装坚强ぢ 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条回答
  •  猫巷女王i
    2020-11-22 15:35

    This is late to the game, but I built this recursive caster. It works for my needs and I think it's relatively complete. It may help you.

    def _parseJSON(self, obj):
        newobj = {}
    
        for key, value in obj.iteritems():
            key = str(key)
    
            if isinstance(value, dict):
                newobj[key] = self._parseJSON(value)
            elif isinstance(value, list):
                if key not in newobj:
                    newobj[key] = []
                    for i in value:
                        newobj[key].append(self._parseJSON(i))
            elif isinstance(value, unicode):
                val = str(value)
                if val.isdigit():
                    val = int(val)
                else:
                    try:
                        val = float(val)
                    except ValueError:
                        val = str(val)
                newobj[key] = val
    
        return newobj
    

    Just pass it a JSON object like so:

    obj = json.loads(content, parse_float=float, parse_int=int)
    obj = _parseJSON(obj)
    

    I have it as a private member of a class, but you can repurpose the method as you see fit.

提交回复
热议问题