简体   繁体   中英

to_json returns string instead of json in Rails

The following piece of code should return a json:

  @series = @series.map do |serie| {
    :name => serie.name,
    :id => serie.id
  }

  @series.to_json

It's return is the following:

"[{\"name\":\"Barra\",\"id\":3},{\"name\":\"Botafogo 1\",\"id\":1},{\"name\":\"Botafogo 2\",\"id\":2},{\"name\":\"Tijuca\",\"id\":4}]"

Why is it returning a string instead of a json?

'json' gem is both installed and required at the top of my .rb file

I've just resolved my problem. For some reason as_json does what I want rather than to_json . I didn't quite understand why. I'll update my answer if I ever find out. That's strange, for to_json worked before I changed my development database form sqlite 3 to postgresql. But I don't think that might be the problem, because it was working nicely with Heroku's postgre database.

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