【问题标题】:How do I stop removing double quotes after passing command-line argument?传递命令行参数后如何停止删除双引号?
【发布时间】:2020-03-19 17:11:44
【问题描述】:

您好,我正在尝试在终端中传递 json 作为有效负载输入,但是在终端中传递参数后,我得到了没有双引号的 json,我也希望我的响应输出为 json 格式。

如何在传递命令行参数后停止删除双引号?

这是我的代码,

def get_apicall():
        Token = get_token()
        url = "http://localhost.../resp"
        Header = {'Content-Type': "application/json", 'Authorization': 'Bearer ' + str(Token)}
        payload = sys.argv[1]
        print(payload)
        payload1 = json.dumps(payload )
        print(payload1)
        response = requests.request("POST", url, data=payload1, headers=Header)
        print(response.text)
    get_endpoint()

我的输入json是{ "request":"success","input":[ { "type":" ", "content":[ { "type":" ", "meta":{ "sample_type":" " , deatail":" "} ] } ], "output":[ { "type":" ","content":[ { "type":"", "meta":{ "sample_type":"", }, "deatils":" " } ] } ] }

当我尝试打印在终端 payload = sys.argv[1] print(payload) 中传递的输入有效负载时

但是当我执行 print(payload) 删除双引号时我得到了这个:{ request:success,input:[ { type: , content:[ { type: , meta:{ sample_type: , deatail: } ] } ], output:[ { type: ,content:[ { type:, meta:{ sample_type:, }, deatils: } ] } ] }

如果我在上面的代码中的某些地方有错误,请纠正我。

我希望print(payload) 与我的输入有效负载相同

{ "request":"success","input":[ { "type":" ", "content":[ { "type":" ", "meta":{ "sample_type":" " , deatail":" "} ] } ], "output":[ { "type":" ","content":[ { "type":"", "meta":{  "sample_type":"",  },  "deatils":" " } ] }  ] }`

【问题讨论】:

  • 如何调用脚本?
  • 你使用的是什么操作系统?
  • 引号,没有引号,重要的是值是什么,它们的类型。请忘记引号,并清楚其值及其类型。

标签: python json python-3.x command-line-arguments


【解决方案1】:

使用print() 函数可以应用不同的打印格式。也许尝试使用repr() 函数,它将根据 Python 解释对象的方式显示对象。 IE。它将包括类型信息,例如字符串的引号、列表的方括号和字典的花括号。

【讨论】:

    【解决方案2】:

    您正在尝试使用 print() 打印 JSON,它会格式化 JSON(删除双引号)。

    如果要在输出中保留引号,请改用 print() 中的 json.dumps() (docs)。也就是说,只需在您的代码中将print(payload) 替换为print(json.dumps(payload))。

    因此,以下代码将为您工作:

    import json
    
    print(json.dumps(payload))
    

    【讨论】:

      猜你喜欢
      • 2018-01-27
      • 2011-10-06
      • 2013-08-31
      • 1970-01-01
      • 2020-10-03
      • 1970-01-01
      • 2020-07-25
      • 1970-01-01
      • 2011-09-03
      相关资源
      最近更新 更多