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

Python中如何移除JSON结果特定部分的双引号?

问题:移除JSON中vouchers字段值的前后双引号,保留内部双引号

原始代码

import json

text = '{"restName":"apple","restaurantTotal":150,"vouchers":null}'
obj = json.loads(text)
print(obj)
if 'banana' not in obj['restName'] and obj['restaurantTotal'] <= 200:
    obj['vouchers'] = '[{"Discount":'+ str(obj['restaurantTotal']/2) +'}]'
result = json.dumps(obj ,separators=(',', ':')).replace('\"','')
print(result)

原始运行结果

{"restName":"apple","restaurantTotal":150,"vouchers":"[{"Discount":75.0}]"}

需求说明

当前结果中vouchers字段的值被双引号包裹,希望仅移除该值前后的双引号,保留内部双引号。

解决方案

方法一:正确构造Python对象(推荐)

问题根源是你将vouchers的值定义为字符串类型的JSON片段,导致json.dumps序列化时自动为其添加双引号。正确做法是直接构造Python列表和字典对象,让json.dumps自动处理序列化:

import json

text = '{"restName":"apple","restaurantTotal":150,"vouchers":null}'
obj = json.loads(text)
print(obj)
if 'banana' not in obj['restName'] and obj['restaurantTotal'] <= 200:
    # 直接构造Python列表+字典,而非字符串
    obj['vouchers'] = [{"Discount": obj['restaurantTotal'] / 2}]
result = json.dumps(obj, separators=(',', ':'))
print(result)

运行结果

{"restName":"apple","restaurantTotal":150,"vouchers":[{"Discount":75.0}]}

方法二:正则表达式精准替换(特殊场景用)

如果因业务限制必须先构造字符串,可通过正则表达式匹配vouchers字段的前后双引号并移除:

import json
import re

text = '{"restName":"apple","restaurantTotal":150,"vouchers":null}'
obj = json.loads(text)
print(obj)
if 'banana' not in obj['restName'] and obj['restaurantTotal'] <= 200:
    obj['vouchers'] = '[{"Discount":' + str(obj['restaurantTotal']/2) + '}]'
result = json.dumps(obj, separators=(',', ':'))
# 匹配vouchers字段的前后双引号并替换
result = re.sub(r'"vouchers":"([^"]+)"', r'"vouchers":\1', result)
print(result)

运行结果

{"restName":"apple","restaurantTotal":150,"vouchers":[{"Discount":75.0}]}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 19:15:04