在httparty中构造一个json请求

时间:2014-09-01 10:03:53

标签: ruby-on-rails ruby json rest httparty

我试图使用Httparty复制以下curl请求但没有成功。我想知道如何最好地使用httparty构建嵌套的json。我见过的任何嵌套查询的例子都没有帮助。我从我尝试访问的API收到500错误。任何帮助表示赞赏

curl https://api.relateiq.com/v2/contacts
-X POST
-u [API Key]:[API Secret]
-H 'Content-Type: application/json'
-H 'Accept: application/json'
-d '{
    "properties" : {
        "name" : [
            {
                "value" : "James McSales"
            }
        ],
        "email" : [
            {
                "value" : "james.mcsales@relateiq.com"
            },
            {
                "value" : "jimmy@personal.com"
            }
        ],
        "phone" : [
            {
                "value" : "(888) 555-1234"
            },
            {
                "value" : "(888) 555-0000"
            }
        ],
        "address": [
            {
                "value": "123 Main St, USA"
            }
        ],
        "company": [
            {
                "value": "RelateIQ"
            }
        ],
        "title": [
            {
                "value": "Noob"
            }
        ]
    }
}'

这是我的httparty请求的缩短版本,

HTTParty.post(
    "https://api.relateiq.com/v2/contacts",
:body => {
        :properties => {
    :name => [{:value => "Falcao Test"}],
    :email => [{:value => "FalcaoTest@monaco.fr"}]
    }
    },
    :basic_auth => auth,
:options => { :headers => { 'Content-Type' => 'application/json' } }
)

并且请求就像这样

https://api.relateiq.com/v2/contacts>,@ options = {:limit => 5,:assume_utf16_is_big_endian => true,:default_params => {},:follow_redirects => true ,:parser => HTTParty :: Parser,:connection_adapter => HTTParty :: ConnectionAdapter,:body => {:properties => {:name => [{:value =>" Falcao测试"}],:email => [{:value =>" FalcaoTest@monaco.fr"}]}},:basic_auth => {:username =>&#34 ; 5400a0b7e4b052e888539fb7",:password =>" WNyLKfLZ9wK1hEyY6249VQKQ4zS"},:options => {:headers => {" Content-Type" =>" application / json"}}},@ last_uri =#https://api.relateiq.com/v2/contacts> ;, @ raw_request =#,@ last_response =#>

我之前使用过httparty,但之前没有使用包含[]嵌套的结构。这让我很困惑

2 个答案:

答案 0 :(得分:0)

你的json与众不同。

你的卷曲示例

    "name" : [
        {
            "value" : "James McSales"
        }
    ],

即键“name”的值是包含一个对象(带键值)的数组

您的httparty代码

 :name => {:value => "Falcao Test"}

所以键“name”的值不再是数组

要匹配原始示例,它应该是

 :name => [{:value => "Falcao Test}]

答案 1 :(得分:0)

我永远无法用HTTParty复制这个结构,这在以前从未发生过。我最终不得不使用curb和一个转义的json字符串