开发者

Posting multiple objects with Ruby/Rails (Badly formed JSON?)

This is more of an "am i doing this right question".

Basically I have your standard client server setup going.

I'm trying to post multiple objects as one to the server. The objects being posted are:

1: A 1d array of strings (pretty straightforward) @headers

2: An array of hashes each of which contain about 7 values and keys. @contentsArray

I figures something like the following would do the trick

    @postedInfo = {:info =>
      {
        :headers =>@headers,
        :content => @contentsArray
      }
    }
    myJsonReq = @postedInfo

    puts "ITS A MAAAAAAAAAAADDDDD HOUUUUUSSSSSEEEEE" #Sorry, I just saw rise of the planet of the apes
    puts myJsonReq.as_json
    res = Net::HTTP.post_form(URI.parse('http://127.0.0.1:3007/update.json'),myJsonReq)

The URL defined is obviously the server but how it comes through is like the following

format: json
action: update_repo
pages: "content Page Title ........."very long string with no brackets or resemblance of JSON" followed by the headers part
headers: all strings are in here
controller: Update

If I create a variable like so

@x = (params[:pages])
and puts @x.class

@x is a string where in other bits of code It would come through as an object. Either array or hash with indifferent access.

Naturally I thought that I has to deserialize it from JSON so I used the line's

JSON.parse(@x)
JSON.parse(params)

both of which threw JSON::ParserError (745: unexpected token at 'content .... and then the rest of the string.

I think I'm sending the objects right or am I constructing them t开发者_JS百科he wrong way?


From the fine manual:

Form data must be represented as a Hash of String to String

You're passing in a Hash of Symbol to Hash. If you dig into the source, you'll see that it ends up going through this:

def set_form_data(params, sep = '&')
  self.body = params.map {|k, v| encode_kvpair(k, v) }.flatten.join(sep)
  self.content_type = 'application/x-www-form-urlencoded'
end

def encode_kvpair(k, vs)
  Array(vs).map {|v| "#{urlencode(k.to_s)}=#{urlencode(v.to_s)}" }
end

If the vs is a Hash (as in your case), you won't get anything useful coming through. For example, apply all that to {:a => {:b => :c}} you'll get this:

"a=[:b,%20:c]"

And that's not terribly useful.

So, if you want to use Net::HTTP.post_form, then you'll have to flatten your data into a simple one level Hash yourself.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜