afxjzs
afxjzs

Reputation: 982

POSTing JSON to API from Ruby on Rails

I am trying to post to this third party API that is (based on node.js and couchDB) There is already a functioning PHP application that is successfully posting to this API, but we are moving ruby on rails and i am trying to get a testsite connected.

In the PHP app, which I did not create, they are using cURL and setting POSTVARS to an encoded variable that appears to be in javascript dot notation.

I am using HTTParty so when I take my post data and convert it to JSON and submit it, it's a no go because with HTTParty, post vars have to be a hash.

When I send the post data without encoding it, I get a malformed JSON error.

Is there a simple way to convert a multidimensional hash into an array of key value pairs where the key is the JSON dot notation for that value?

I've looked at these articles for solutions, but i'm pretty new to ruby and rails, so I haven't made much progress yet.

http://www.goodercode.com/wp/convert-your-hash-keys-to-object-properties-in-ruby/

This is a great article, but I'm not sure how you implement that code. I put it in a hashify.rb file in the /lib directory and restarted, but it didn't seem to work at all.

I've also tried writing a class like this:

class Hashify

 def initialize(hash)
   hash.each do |k, v|

     k=k.gsub(/\.|\s|-|\/|\'/, '_').downcase.to_sym

     self.instance_variable_set("@#{k}", v) ## create and initialize an instance variable for this key/value pair
     self.class.send(:define_method, k, proc { self.instance_variable_get("@#{k}") }) ## create the getter that returns the instance variable
     self.class.send(:define_method, "#{k}=", proc { |v| self.instance_variable_set("@#{k}", v) }) ## create the setter that sets the instance variable
   end
 end
end

From here

I need it to be recursive.

Upvotes: 0

Views: 730

Answers (2)

seph
seph

Reputation: 6076

"Jbuilder gives you a simple DSL for declaring JSON structures that beats massaging giant hash structures."

This might be what you are looking for:

https://github.com/rails/jbuilder

Upvotes: 1

Daniel Lv
Daniel Lv

Reputation: 865

I'm not quite sure what is your real problem, but Rails provider a VERY SIMPLE way to convert hash to params, but it probably not fit your problem.

>> {:a => {:b => :c}}.to_param
=> "a%5Bb%5D=c"

Upvotes: 2

Related Questions