Json.dump失败,“必须是unicode,而不是str”TypeError [英] Json.dump failing with 'must be unicode, not str' TypeError
问题描述
io.open
将其加载到我的python 2.7脚本中,如下所示:with io.open('multiIdName.json',encoding =utf-8)as json_data:
/ pre>
cards = json.load(json_data)
我添加一个新的属性到json,都很好。然后我尝试将其写回另一个文件:
with io.open(testJson.json,'w' ,encoding =utf-8)作为outfile:
json.dump(cards,outfile,ensure_ascii = False)
这是当我收到错误
TypeError:必须是unicode,而不是str
我尝试将outfile作为二进制文件(
与io.open(testJson.json,wb)作为outfile:
),但我最终得到的东西: / p>
{multiverseid:262906,name:\\\æ\\\¸\\\¸\\\é\\\ \\\¼\\\ç\\\\\\¹\\\é\\\¹\\\«,language:简体中文}
我认为以相同的编码开放和写入就足够了,还有ensure_ascii标志,但显然不是。我只想在运行我的脚本之前保留文件中存在的字符,而不转换成\u的。
解决方案你可以尝试以下吗?
with io.open(testJson.json,'w',encoding =utf -8)作为outfile:
outfile.write(unicode(json.dumps(cards,ensure_ascii = False)))
I have a json file which happens to have a multitude of Chinese and Japanese (and other language) characters. I'm loading it into my python 2.7 script using
io.open
as follows:with io.open('multiIdName.json', encoding="utf-8") as json_data: cards = json.load(json_data)
I add a new property to the json, all good. Then I attempt to write it back out to another file:
with io.open("testJson.json",'w',encoding="utf-8") as outfile: json.dump(cards, outfile, ensure_ascii=False)
That's when I get the error
TypeError: must be unicode, not str
I tried writing the outfile as a binary (
with io.open("testJson.json",'wb') as outfile:
), but I end up with stuff this:{"multiverseid": 262906, "name": "\u00e6\u00b8\u00b8\u00e9\u009a\u00bc\u00e7\u008b\u00ae\u00e9\u00b9\u00ab", "language": "Chinese Simplified"}
I thought opening and writing it in the same encoding would be enough, as well as the ensure_ascii flag, but clearly not. I just want to preserve the characters that existed in the file before I run my script, without them turning into \u's.
解决方案Can you try the following?
with io.open("testJson.json",'w',encoding="utf-8") as outfile: outfile.write(unicode(json.dumps(cards, ensure_ascii=False)))
这篇关于Json.dump失败,“必须是unicode,而不是str”TypeError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!