【问题标题】:Is there an alternative to Json.dump which outputs an Array?是否有替代 Json.dump 输出数组的替代方法?
【发布时间】:2022-01-01 11:22:52
【问题描述】:

我正在创建一个 PUT 请求,该请求将在有效负载中发送 requires a JSON object Array。我已将数据放入一个数组中,并确认它是 Array 类,但是当它作为参数提供给 Json.dump() 时,它会作为字符串对象输出,这会导致 500 内部服务器错误,是否有替代方法推送数据的方法,这将保持其原始格式?

  def call_api

  url = URI("url.zendesk.com/api/v2/macros/update_many")

  https = Net::HTTP.new(url.host, url.port)
  https.use_ssl = true

  request = Net::HTTP::Put.new(url)
  request["Authorization"] = "Basic ="
  request["Content-Type"] = "application/json"
  request.body = JSON.dump(@data) #outputs a string, should be a json array
  response = https.request(request)
end

回复 => #<Net::HTTPInternalServerError 500 Internal Server Error readbody=true>

【问题讨论】:

  • 响应的正文是什么?
  • @Schwern 这是 "{\"status\":\"500\",\"error\":\"Internal Server Error\"}"

标签: json ruby


【解决方案1】:

...但是当它作为参数提供给 Json.dump() 时,它会作为字符串对象输出

根据定义,JSON 是一个字符串。它获取数据并将其转换为字符串,然后可以将其转换回数据。这是serialization。所以那部分很好。

您可能需要向您的 URL 添加一个方案,例如 https。较新版本的 Net::HTTP 甚至不会接受没有方案的 URI。这可能是 500 错误的来源。

查看the API documentation,正确的URL以.json结尾。

url = URI("https://url.zendesk.com/api/v2/macros/update_many.json")

它不需要一个数组,它需要一个像这样的对象。弄错这种格式会导致 400 Bad Request。

@data = {
  "macros": [
    {
      "active": false,
      "id": 25
    },
    {
      "id": 23,
      "position": 5
    }
  ]
}

最后,还有an official Zendesk Ruby API client,它可能更容易使用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-06
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 2015-02-12
    • 1970-01-01
    • 2015-11-14
    • 1970-01-01
    相关资源
    最近更新 更多