rails to_json remove quote

2k views Asked by At

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

3

There are 3 answers

6
whodini9 On BEST ANSWER

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.

0
ydaniju On

You can use JSON.parse(create_servicetag_report_request.body[:hostIds]) to parse it.

0
spickermann On

Just remove the join part from this line:

host_ids = LmiHost.all.collect { |lmi| lmi.host_id }.join ', '

join joins your array of ids into a comma separated string. This doesn't seems to be what you want.

Btw. you can shorten .collect { |lmi| lmi.host_id } to map(&:host_id):

create_servicetag_report_request.body = {
  hostIds: LmiHost.all.map(&:host_id), 
  fields:  'ServiceTag'
}.to_json