How to encode Chinese character as 'gbk' in json, to format a url request parameter String?
Question: I want to dump a dict as a json String which contains some Chinese characters,
and format a url request parameter with that.

here is my python code:

    
    
    import httplib
    import simplejson as json
    import urllib
    
    d={
      "key":"上海",
      "num":1
    }
    
    jsonStr = json.dumps(d,encoding='gbk')
    url_encode=urllib.quote_plus(jsonStr)
    
    conn = httplib.HTTPConnection("localhost",port=8885)
    conn.request("GET","/?json="+url_encode)
    res = conn.getresponse()
    

what I expected of the request string is this:

    
    
    GET /?json=%7B%22num%22%3A+1%2C+%22key%22%3A+%22%C9%CF%BA%A3%22%7D
                                                    ------------
                                                         |
                                                         V
                           "%C9%CF%BA%A3" represent "上海" in format of 'gbk' in url.
    

but what I got is this:

    
    
    GET /?json=%7B%22num%22%3A+1%2C+%22key%22%3A+%22%5Cu6d93%5Cu5a43%5Cu6363%22%7D
                                                    ------------------------
                                                             |
                                                             v
               %5Cu6d93%5Cu5a43%5Cu6363  is 'some' format of chinese characters "上海"  
    

I also tried to dump json with `ensure_ascii=False` option:

    
    
    jsonStr = json.dumps(d,ensure_ascii=False,encoding='gbk')
    

but get no luck.

so, how can I make this work? thanks.


Answer: You almost got it with `ensure_ascii=False`. This works:

    
    
    jsonStr = json.dumps(d, encoding='gbk', ensure_ascii=False).encode('gbk')
    

You need to tell `json.dumps()` that the strings it will read are GBK, and
that it should not try to ASCII-fy them. Then you must re-specify the output
encoding, because `json.dumps()` has no separate option for that.

This solution is similar to another answer here:
<http://stackoverflow.com/a/18337754/4323>

So this does what you want, though I should note that the standard for URIs
seems to say that they should be in UTF-8 whenever possible. For more on this,
see here: <http://stackoverflow.com/a/14001296/4323>

