Adam
Adam

Reputation: 683

HTTParty is escaping JSON

I'm using HTTParty to send data to a remote API, however the API is complaining because the JSON being sent by HTTParty appears to be being escaped, and is thus deemed invalid.

Here's what I'm doing:

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}]}

Calling to_json on query escapes the JSON too:

"{\"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}]}"

Is this expected behavior to escape the JSON? Or I'm wondering if the hash I'm building for query is invalid for JSON purposes?

Any help would be greatly appreciated.

Upvotes: 2

Views: 814

Answers (1)

EugZol
EugZol

Reputation: 6545

Calling to_json on query doesn't yield escaped JSON.

Try puts query.to_json to see that.

You see backslashes because #inspect method on String (and this method is called to display contents of variables to console) displays String enclosed in double quotes, and it has to escape quotes which are in the given string itself.

Your problem is probably not having proper Content-Type headers. You should do something like this:

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

Upvotes: 3

Related Questions