I am trying to convert a bytes
field to str
. I tried the following code. Not sure, why it is adding an extra char
before and after each key
and value
.
print(event_json)
print(type(event_json))
event_json_nobytes = event_json.decode('utf-8')
event_obj = json.dumps(event_json_nobytes, indent=2)
print(event_obj)
print(type(event_json_nobytes))
output:
b'{"specversion": "1.0", "id": "xxxxyy", "source": "campaign", "type": "clientfed", "datacontenttype": "H8908", "time": "2024-01-27T11:51:19.288Z", "data": {"clientIdentifier": "H7508", "portfolioIdentifier": "H8908"}}'
<class 'bytes'>
"{"specversion": "1.0", "id": "xxxxyy", "source": "campaign", "type": "clientfed", "datacontenttype": "H8908", "time": "2024-01-27T11:51:19.288Z", "data": {"clientIdentifier": "H7508", "portfolioIdentifier": "H8908"}}"
<class 'str'>
Any lead in this regard will be really helpful. Thank you.
P.S. – I got the event_json
field from a cloudevents
output.
10
print(event_json)
print(type(event_json))
event_json_nobytes = event_json.decode('utf-8')
At this point, event_json_nobytes is a string, and your mission is done if you just want to go from bytes
to str
.
Now, if your goal is to reformat this string, you first need to load it before re-dumping it indented :
event_obj = json.dumps(json.loads(event_json_nobytes), indent=2)