0

I'm following some API docs and as part of a post I need to generate some JSON in this format:

{
 "panelist": {
 "email_address": "[email protected]",
 "gender": "m",
 "postal_code": "12345",
 "year_of_birth": 1997,
 “variables”: [1000,1001]
 }
}

What's the best way to generate this in Rails (I don't have a Panelist model, rather most of these things are stored in my Appuser model, so gender will actually be @appuser.gender).

In the past I've just done something like

params = {
 "gender" => "m",
 "postal_code" => "12345"
}

and then in my request set_form_data:

http = Net::HTTP.new(uri.host, uri.port)

request = Net::HTTP::Post.new(uri.request_uri)
request.set_form_data(params)

response = http.request(request)

But the nested params inside panelist are throwing me off.

I did try using the to_json to simply do this:

appuser = { "panelist" => { "email" => "[email protected]", "zip" => "12345" } }
appuser.to_json
 => "{\"panelist\":{\"email\":\"[email protected]\",\"zip\":\"12345\"}}" 

But it seems like I'm more or less just hardcoding the json. Which I suppose I could do, but it feels like there could be an easier way.

4
  • How often are you going to send data in this format? If it is more than once, I would consider making a model for it. Commented Dec 28, 2015 at 18:00
  • Pretty often. I'll look into the new model. I was initially leaning away from that since the data already existed in the appuser model. Commented Dec 28, 2015 at 18:03
  • If this model is a subset of the AppUser model, then the AppUser could have a method which returns one of these. Then you just call AppUser.to_special_model.to_json Commented Dec 28, 2015 at 18:06
  • Ah, good thought! :) Commented Dec 28, 2015 at 18:08

1 Answer 1

1

There is a helper library, 'json', that adds a 'to_json' method to every object. Just add a require for this, and then call params.to_json.

How to convert a ruby hash object to JSON?

Sign up to request clarification or add additional context in comments.

3 Comments

I'm not sure I want to override it for this though - as I actually need the to_json method for interaction in my app via my Backbone front-end. This piece is solely for interaction with the outside service...
It only adds the method to objects that have not already defined it themselves. If you have a model which declares its own 'to_json', then that will still be used when you call it.
Played around a bit and added an edit using the to_jsoncall

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.