简体   繁体   English

Python 2.7> 3.5 JSON转储“不是字符串”

[英]Python 2.7 > 3.5 JSON dumps “is not a string”

I am converting my code from Python 2.7 to 3.5 but run into some issues while dumping JSON data into a file. 我将代码从Python 2.7转换为3.5,但是在将JSON数据转储到文件时遇到了一些问题。

Originally the code for 2.7 was like this: 最初2.7的代码是这样的:

backlog_json = json.dumps(backlog, indent=2, sort_keys=True)
f = open(backlog_path,"wt")
f.write(backlog_json)
f.close()

Currently the same code gives the following error: 当前,相同的代码给出以下错误:

TypeError: key b'00c4349c-9617-42c3-a0a3-8e16262bcd76' is not a string

It seems to do something with bytes, while I just want all items in my JSON to be strings. 它似乎与字节有关,而我只是希望JSON中的所有项目都是字符串。

for some reason b' is added to the dict data: 由于某些原因,将b'添加到dict数据中:

b'f91de40f-cf15-4da6-bee9-0101920c8874':

You need to convert any keys that are byte literals with strings. 您需要用字符串转换任何为字节文字的键。 you can make the swap-with str(bytes_string, 'utf-8') but first you have to find them. 您可以使用str(bytes_string, 'utf-8')进行交换str(bytes_string, 'utf-8')但首先必须找到它们。 If it is obvious where these byte literals exist you can write code to switch them out or you could convert like this... 如果很明显这些字节文字存在的地方,您可以编写代码将其切出,也可以像这样进行转换...

def reqked(ob):
    if(type(ob) == dict):
        for(k in ob.keys()):
            if(type(k) == bytes):
                ob[str(k, 'utf-8')] = reqked(ob[k])
                del ob[k]
            else:
                ob[k] = reqked(ob[k])
    elif(type(ob) == list):
        for k in range(0,len(ob)):
            ob[k]=reqked(ob[k])
    elif(type(ob) == bytes):
        ob = str(bytes_string, 'utf-8')
    return(ob)

You have to convert your byte data into string one 您必须将字节数据转换为字符串一

file = open(file_name, encoding='utf8')
json_data = json.load(file)
file.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM