【问题标题】:HTTParty is escaping JSONHTTParty 正在转义 JSON
【发布时间】:2015-07-31 20:07:52
【问题描述】:

我正在使用 HTTParty 向远程 API 发送数据,但是 API 抱怨,因为 HTTParty 发送的 JSON 似乎被转义,因此被视为无效。

这就是我正在做的事情:

query = {"count"=>1,
 "workspaces"=>
  {123445=>
    {"title"=>"Test Project",
     "description"=>"",
     "start_date"=>"2015-06-01T00:00:00.000Z",
     "due_date"=>"2015-08-31T00:00:00.000Z",
     "price_in_cents"=>8000,
     "currency"=>"USD",
     "status_key"=>130,
     "custom_field_values_attributes"=>[],
     "workspace_groups_attributes"=>
      [{"created_at"=>"2015-07-13T11:06:36-07:00",
        "updated_at"=>"2015-07-13T11:06:36-07:00",
        "name"=>"Test Customer",
        "company"=>true,
        "contact_name"=>nil,
        "email"=>nil,
        "phone_number"=>nil,
        "address"=>nil,
        "website"=>nil,
        "notes"=>nil,
        "id"=>"530947",
        "custom_field_values_attributes"=>[]}],
     "id"=>123445}},
 "results"=>[{"key"=>"workspaces", "id"=>123445}]}

query 上调用 to_json 也会转义 JSON:

"{\"count\":1,\"workspaces\":{\"123445\":{\"title\":\"Test Project\",\"description\":\"\",\"start_date\":\"2015-06-01T00:00:00.000Z\",\"due_date\":\"2015-08-31T00:00:00.000Z\",\"price_in_cents\":8000,\"currency\":\"USD\",\"status_key\":130,\"custom_field_values_attributes\":[],\"workspace_groups_attributes\":[{\"created_at\":\"2015-07-13T11:06:36-07:00\",\"updated_at\":\"2015-07-13T11:06:36-07:00\",\"name\":\"Test Customer\",\"company\":true,\"contact_name\":null,\"email\":null,\"phone_number\":null,\"address\":null,\"website\":null,\"notes\":null,\"id\":\"530947\",\"custom_field_values_attributes\":[]}],\"id\":123445}},\"results\":[{\"key\":\"workspaces\",\"id\":123445}]}"

这是逃避 JSON 的预期行为吗?或者我想知道我为 query 构建的哈希是否对 JSON 无效?

任何帮助将不胜感激。

【问题讨论】:

  • 看起来不错,你控制远程服务器吗?
  • 嘿@Adam!您对这个问题还有其他问题吗? :)

标签: ruby-on-rails ruby json httparty


【解决方案1】:

在查询中调用 to_json 不会产生转义的 JSON。

试试puts query.to_json 看看。

您会看到反斜杠,因为 String 上的 #inspect 方法(调用此方法以将变量的内容显示到控制台)显示用双引号括起来的 String,并且它必须转义给定字符串本身中的引号。

您的问题可能是没有正确的 Content-Type 标头。你应该这样做:

result = HTTParty.post(url, body: query.to_json, headers: {'Content-Type' => 'application/json'})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-14
    • 1970-01-01
    • 2020-10-05
    • 1970-01-01
    • 2014-10-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多