[英]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. 我正在使用HTTParty将数据发送到远程API,但是API抱怨是因为HTTParty发送的JSON似乎已被转义,因此被视为无效。
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: 在
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}]}"
Is this expected behavior to escape the JSON? 这是逃避JSON的预期行为吗? Or I'm wondering if the hash I'm building for
query
is invalid for JSON purposes? 或者我想知道我为
query
而构建的哈希对于JSON目的是否无效?
Any help would be greatly appreciated. 任何帮助将不胜感激。
Calling to_json on query doesn't yield escaped JSON. 在查询上调用to_json不会产生转义的JSON。
Try puts query.to_json
to see that. 尝试
puts query.to_json
。
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. 您会看到反斜杠,因为String上的
#inspect
方法(调用此方法以将变量的内容显示到控制台)将String括在双引号中,并且必须转义给定字符串本身的引号。
Your problem is probably not having proper Content-Type headers. 您的问题可能是没有正确的Content-Type标头。 You should do something like this:
您应该执行以下操作:
result = HTTParty.post(url, body: query.to_json, headers: {'Content-Type' => 'application/json'})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.