Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
165 views
in Technique[技术] by (71.8m points)

Remove unicode character from python when sending response back to javascript

elif self.path == "/recQuery":
  content_length = int(self.headers.getheader('content-length'))
cont_Length = content_length
print "Query Received"
body = self.rfile.read(content_length)
keywords = body.replace("", "")
result = json.loads(keywords)
query = result['query']

r = requests.get('http://example.com') // This returns the JSON
print r.json()
self.wfile.write(r.json()) // Send response back to the javascript
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to encode your output.

If I were you I'll use python3, since python2 encoding is a headache. Anyways I made a super encoding function to help you:

def encode_dict(dic, encoding='utf-8'):
    new_dict={}

    for key, value in dic.items():

        new_key=key.encode(encoding)

        if isinstance(value, list):
            new_dict[new_key]=[]
            for item in value:
                if isinstance(item, unicode):
                    new_dict[new_key].append(item.encode(encoding))

                elif isinstance(item, dict):

                    new_dict[new_key].append(decode_dict(item))

                else:
                    new_dict[new_key].append(item)

        elif isinstance(value, unicode):
            new_dict[new_key]=value.encode(encoding)

        elif isinstance(value, dict):
            new_dict[new_key]=decode_dict(value)

    return new_dict

So you do: self.wfile.write(encode_dict(r.json()))


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...