I'm following some API docs and as part of a post I need to generate some JSON in this format:
{
"panelist": {
"email_address": "test@example.com",
"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" => "test@example.com", "zip" => "12345" } }
appuser.to_json
=> "{\"panelist\":{\"email\":\"test@example.com\",\"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.