简体   繁体   中英

Rails Generate JSON for API POST

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.

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM