【问题标题】:Convert complex object to x-www-form-urlencoded将复杂对象转换为 x-www-form-urlencoded
【发布时间】:2021-10-17 04:54:29
【问题描述】:

我有一个这样的对象:

{
    "someList": [
        {
            "accountNumber": 123456,
            "balance": 3.14
        },
        {
            "accountNumber": 7890,
            "balance": 2.72
        }
    ],
    "numErrors": 0,
    "duration": 12345
}

如何将其转换为 x-www-form-urlencoded 以便使用例如 POST 请求发送它卷曲命令行?我知道"key1=value1&key2=value2",但我特别困惑如何发送包含结构的整个列表。

【问题讨论】:

    标签: json curl post x-www-form-urlencoded


    【解决方案1】:

    我想这完全取决于您要发布到的服务器。
    如果它以 urlencoded 形式接受您的美化 JSON,那么 --data-urlencode @input.json 就足够了 curl。如果没有,您必须先对其进行缩小/序列化,然后像 这样的 JSON 解析器可以提供帮助:

    $ xidel -s input.json -e 'serialize($json,{"method":"json"})'
    {"someList":[{"accountNumber":123456,"balance":3.14},{"accountNumber":7890,"balance":2.72}],"numErrors":0,"duration":12345}
    
    $ xidel -s input.json -e 'serialize($json,{"method":"json"})' | \
      curl -s --data-urlencode @- "<url>"
    
    $ xidel -s input.json -e 'uri-encode(serialize($json,{"method":"json"}))'
    %7B%22someList%22%3A%5B%7B%22accountNumber%22%3A123456%2C%22balance%22%3A3.14%7D%2C%7B%22accountNumber%22%3A7890%2C%22balance%22%3A2.72%7D%5D%2C%22numErrors%22%3A0%2C%22duration%22%3A12345%7D
    
    $ xidel -s input.json -e 'uri-encode(serialize($json,{"method":"json"}))' | \
      curl -s -d @- "<url>"
    

    xidel也可以做POST请求:

    $ xidel -s \
      -d '{uri-encode(serialize(json-doc("input.json"),{"method":"json"}))}' \
      "<url>" \
      -e '$raw'
    
    $ xidel -s input.json -e '
      x:request({
        "post":uri-encode(serialize($json,{"method":"json"})),
        "url":"<url>"
      })/raw
    '
    
    • -e '$raw' 显示原始输出,类似于 curl
    • xidel -s input.json -d '...$json...' 不起作用,因为 -d 在读取输入之前被评估,因此 json-doc() 在查询中打开文件/url。

    【讨论】:

    • 谢谢,关于 xidel 的有趣信息,我以前不知道。但是,虽然输出是 urlencoded,但它仍然是 JSON,而不是 x-www-form-urlencoded,其格式为“property=value&property=value”。我发现我的服务器实际上无论如何都可以接受 JSON,但前提是您为其提供正确类型的 Content-Encoding 标头并使用 --data-raw curl 选项。
    • @k314159 如果您的服务器明确需要标头,那么您必须添加-H "Content-Type application/x-www-form-urlencoded"。与curl 不同,xidel 默认不添加此标头。
    猜你喜欢
    • 2021-06-15
    • 2018-06-11
    • 2015-08-16
    • 2020-10-06
    • 2019-12-04
    • 1970-01-01
    • 1970-01-01
    • 2020-08-21
    • 2020-04-06
    相关资源
    最近更新 更多