Saving utf-8 texts in json.dumps as UTF8, not as \u escape sequence

前端 未结 12 930
说谎
说谎 2020-11-21 23:25

sample code:

>>> import json
>>> json_string = json.dumps(\"ברי צקלה\")
>>> print json_string
\"\\u05d1\\u05e8\\u05d9 \\u05e6\\u05         


        
12条回答
  •  不思量自难忘°
    2020-11-22 00:12

    Thanks for the original answer here. With python 3 the following line of code:

    print(json.dumps(result_dict,ensure_ascii=False))
    

    was ok. Consider trying not writing too much text in the code if it's not imperative.

    This might be good enough for the python console. However, to satisfy a server you might need to set the locale as explained here (if it is on apache2) http://blog.dscpl.com.au/2014/09/setting-lang-and-lcall-when-using.html

    basically install he_IL or whatever language locale on ubuntu check it is not installed

    locale -a 
    

    install it where XX is your language

    sudo apt-get install language-pack-XX
    

    For example:

    sudo apt-get install language-pack-he
    

    add the following text to /etc/apache2/envvrs

    export LANG='he_IL.UTF-8'
    export LC_ALL='he_IL.UTF-8'
    

    Than you would hopefully not get python errors on from apache like:

    print (js) UnicodeEncodeError: 'ascii' codec can't encode characters in position 41-45: ordinal not in range(128)

    Also in apache try to make utf the default encoding as explained here:
    How to change the default encoding to UTF-8 for Apache?

    Do it early because apache errors can be pain to debug and you can mistakenly think it's from python which possibly isn't the case in that situation

提交回复
热议问题