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

如何在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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 05:25:37