A function is returning a dictionary, which has data of type byte. Because it's inside, it gave a dictionary, I couldn't do a simple conversion, using
value.decode('ISO-8859-1')
I would need to go through the entire dictionary and its internal data certifying the data type to overwrite it with the decode. To simulate, I left an example code that returns the same error:
import json
dictionary ={
"id": "04",
"name": "sunil",
"code": b"HR"
}
json_object = json.dumps(dictionary, indent = 4)
print(json_object)
I would like to convert this internal byte data inside a dictionary into some str, so that I could generate the json .
CodePudding user response:
import json
dictionary ={
"id": "04",
"name": "sunil",
"code": b"HR".decode('UTF-8')
}
json_object = json.dumps(dictionary, indent = 4)
print(type(json_object))
Not sure if your dict had a error in it? But if not try this?
CodePudding user response:
I solved my problem with this recursive function.
def decodeDictionary(dictionary):
if type(dictionary) == dict:
for key in dictionary.keys():
dictionary[key] = decodeDictionary(dictionary[key])
elif type(dictionary[key]) == bytes:
dictionary = dictionary.decode('ISO-8859-1')
return dictionary