Reputation: 1
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 .
Upvotes: 0
Views: 1075
Reputation: 1
The previous solution is correct, but it has an issue with a local variable. It will return an error:
cannot access local variable 'key' where it is not associated with a value.
Just modify the code to be:
def decodeDictionary(dictionary):
if type(dictionary) == dict:
for key in dictionary.keys():
dictionary[key] = decodeDictionary(dictionary[key])
elif type(**dictionary**) == bytes:
dictionary = dictionary.decode('ISO-8859-1')
return dictionary
Upvotes: 0
Reputation: 1
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
Upvotes: 0
Reputation: 150
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?
Upvotes: 0