Search code examples
ruby-on-railsjsonrubynet-http

rails to_json remove quote


I am working the the LogMeIn Central API and in the body of my request I need to send some Json. I have this:

  host_ids = LmiHost.all.collect {|lmi| lmi.host_id}.join ', '
  create_servicetag_report_request.body = {hostIds: host_ids, fields: 'ServiceTag'}.to_json

This turns the body into

{\"hostIds\":\"5888, 6225, 214752\",\"fields\":\"ServiceTag\"}

how can i remove the

\"

from this section:

\"5888, 6225, 214752\"

it is not suppose to have quotes around it.

I am using Ruby on Rails


Solution

  • The reason to_json adds the \" (escaped quotations) is because it is converting hostIds as a string. In your rails console try this to see the difference.

    {"hostids":[0,1,2,3]}.to_json
    => "{\"hostids\":[0,1,2,3]}"
    
    {"hostids":"[0,1,2,3]"}.to_json
    => "{\"hostids\":\"[0,1,2,3]\"}"
    

    This can be seen another way by trying: puts [1,2,3,4] vs puts "[1,2,3,4]"

    Ultimately I would refer to the LMI Central API to figure out exactly how multiple hostIds can be sent.