You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将bytes转换为str时出现额外转义字符问题求助

问题:Bytes转Str后JSON出现多余转义字符

尝试将bytes类型字段转换为str类型,转换后每个key和value前后都被添加了额外的转义字符,不清楚原因。event_json字段来自cloudevents的输出。

代码

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))

输出

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'>

原因分析

  • event_json.decode('utf-8')已经把bytes转换成了JSON格式的字符串,它本身就是合法的JSON文本。
  • 后续调用json.dumps()时,会把这个JSON字符串当作普通Python字符串处理,为了符合JSON语法规则,自动给字符串里的双引号加上转义符\,导致出现多余的转义。

解决方法

根据需求选一种即可:

  1. 直接使用解码后的字符串:如果只需要JSON文本内容,解码后直接用event_json_nobytes,不用再调用json.dumps()。
    修改后代码:
    print(event_json)
    print(type(event_json))
    event_json_nobytes = event_json.decode('utf-8')
    print(event_json_nobytes)
    print(type(event_json_nobytes))
    
  2. 解析为Python对象后再序列化:如果需要操作JSON对应的字典/列表,先用json.loads()把解码后的字符串转成Python对象,再按需用json.dumps()序列化(比如要格式化输出)。
    修改后代码:
    import json
    
    print(event_json)
    print(type(event_json))
    event_json_nobytes = event_json.decode('utf-8')
    event_obj = json.loads(event_json_nobytes)
    formatted_json = json.dumps(event_obj, indent=2)
    print(formatted_json)
    print(type(event_obj))
    

内容的提问来源于stack exchange,提问作者SDS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 20:26:18