1

I have a method where I receive data from 3rd party something like this

def func(**kwagrs):
    print kwagrs

output
{'payload': u'{"id":"50b4f4b3e319586b10230f68d21f5edb","data":{"message":"message is \\u00a3 150 \\u2192\\u00c5\\u25024\\u00e9","length":47}}'}

How to convert \\u00a3 to £ in python also, you have notice value type for the payload is Unicode not dictionary or JSON
I tried to find the similar issue in StackOverflow but didn't find any solution.

Vinay
  • 75
  • 8

1 Answers1

0

With aid of ValueError: unichr() arg not in range(0x10000) (narrow Python build), I came to

import struct
def unichar(i):
    try:
        return unichr(i)
    except ValueError:
        return struct.pack('i', i).decode('utf-32')

def func(arg):
    msg = args['payload']['data']['message']
    # msg = 'message is \\u00a3 150 \\u2192\\u00c5\\u25024\\u00e9'
    print ' '.join(''.join([unichar(int(ch, 16)) for ch in chunk.split('\\u')[1:]]) if chunk.startswith('\\u') else
    chunk for chunk in msg.split(' '))

func({'payload':{'data':{'message':"message is \\u00a3 150 \\u2192\\u00c5\\u25024\\u00e9"}}})

If we run the code above, we get message is £ 150 →Åé. Note: We may have better parsing code...

Jo Shinhaeng
  • 36
  • 1
  • 4