How to get string objects instead of Unicode from JSON?

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

    So, I've run into the same problem. Guess what was the first Google result.

    Because I need to pass all data to PyGTK, unicode strings aren't very useful to me either. So I have another recursive conversion method. It's actually also needed for typesafe JSON conversion - json.dump() would bail on any non-literals, like Python objects. Doesn't convert dict indexes though.

    # removes any objects, turns unicode back into str
    def filter_data(obj):
            if type(obj) in (int, float, str, bool):
                    return obj
            elif type(obj) == unicode:
                    return str(obj)
            elif type(obj) in (list, tuple, set):
                    obj = list(obj)
                    for i,v in enumerate(obj):
                            obj[i] = filter_data(v)
            elif type(obj) == dict:
                    for i,v in obj.iteritems():
                            obj[i] = filter_data(v)
            else:
                    print "invalid object in data, converting to string"
                    obj = str(obj) 
            return obj
    

提交回复
热议问题