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": "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.

Tom Hammond
  • 5,842
  • 12
  • 52
  • 95

1 Answers1

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?

Community
  • 1
  • 1
Andrew Williamson
  • 8,299
  • 3
  • 34
  • 62
  • 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... – Tom Hammond Dec 28 '15 at 17:52
  • 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. – Andrew Williamson Dec 28 '15 at 17:53
  • Played around a bit and added an edit using the `to_json`call – Tom Hammond Dec 28 '15 at 18:00