Wednesday, March 25, 2015

python source code to Convert dictionary / list of strings from Unicode to python string

while using a unicode, we can come to the situation that we have data in unicode and are supposed to convert in ASCII. Here I have written a simple python code to convert dictionary from unicode to ASCII.

in using unicode, if we have simple unicode data as a= u"hello". Then we can easily use a.encode('utf-8') and we can get the desired result in python string. However if we have data in dictionary or tuple or list then in such case we cannot use encode as before .

Source Code:


#!/usr/bin/env python

import json

def convert(input):
    if isinstance(input, dict):
        return {convert(key): convert(value) for key, value in input.iteritems()}
    elif isinstance(input, list):
        return [convert(element) for element in input]
    elif isinstance(input, unicode):
        return input.encode('utf-8')
    else:
        return input



data={
    "books": [
        {
            "id": "1",
            "name": "Mathematics",
            "type": "Engineering",
            
            "run_at": {"day": "*/1", "second": 5},
            "start_date": "2011-12-21 17:00:23",


         
            "interval_type": "day",
            "timezone": "Asia/Kathmandu"
        },
        {
            "id": "124",
            "name": "Data Mining",
            "type": "Engineering",
            "run_at": {"second": 0},

           
            "interval_type": "day",
            "timezone": "Asia/Kathmandu"
        }
    ]
}

test = json.dumps(data)
valid_data = json.loads(test)
final_data = convert(valid_data)
print final_data




data1= [ { 'a':'A', 'b':(2, 4), 'c':3.0 } ]
test1 = json.dumps(data1)

valid_data1 = json.loads(test1)

final_data1 = convert(valid_data1)

print final_data1


here I have a dictionary and tuple data type and first I encoded to unicode by using json.load . Later I have writted a convert function which takes a unicode dictionary data then it encodes in to the python string.

No comments:

Post a Comment