如何在JSON格式的data变量中正确嵌入credentials变量?
解决方案
以下几种方法可以解决你的问题:
方法1:使用f-string并转义大括号
外层用单引号时,f-string里需要输出的大括号要写成{{和}},同时用双引号包裹credentials变量以符合JSON格式:credentials = str(inputtxt.get()) + str(inputtxt2.get()) data = f'{{"name":"{credentials}", "private":true}}'方法2:直接字符串拼接
将字符串拆分为固定部分和变量部分,通过加号拼接,同样用双引号包裹变量值:credentials = str(inputtxt.get()) + str(inputtxt2.get()) data = '{"name":"' + credentials + '", "private":true}'方法3:使用json模块(推荐)
先构造Python字典,再通过json.dumps()转换为JSON字符串,无需手动处理引号转义,尤其适合包含特殊字符的场景:import json credentials = str(inputtxt.get()) + str(inputtxt2.get()) data_dict = {"name": credentials, "private": True} data = json.dumps(data_dict)注:这里
private使用Python布尔值True,转换后会自动变成JSON格式的true。
内容的提问来源于stack exchange,提问作者Xpray 935
相关产品推荐
相关产品推荐

