删除python中特定部分的双引号

xpcnnkqh  于 2023-05-05  发布在  Python
关注(0)|答案(1)|浏览(146)
import json,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=(',', ':')).replace("\\","")
print(result)

结果

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

我想删除这部分的双引号只有(")[{"Discount":75.0}](")有什么办法吗?

dy2hfwbg

dy2hfwbg1#

不要将值写成字符串。json.dumps可以处理这个问题。

obj['vouchers'] = [{"Discount": obj['restaurantTotal'] / 2}]
result = json.dumps(obj)

相关问题