14

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

6
  • 4
    json is meant to be a string Commented Apr 21, 2013 at 17:25
  • I believe not. iOS JSON parser won't parse it, nor will my JSON prettifier plugin for Safari. I wonder maybe rails is not returning some content-type? Commented Apr 21, 2013 at 17:28
  • How are you trying to parse it? Code? Commented Apr 21, 2013 at 17:29
  • Yes, @Dogbert, I parse it in iOS. The JSON parser class raises an exception for the return is a plain string. Commented Apr 21, 2013 at 17:31
  • 1
    I think you are confused. JSON is a language for serializing objects. So the natural representation of JSON itself is a string. IOS has some very slick classes for turning JSON stored in NSData objects into Foundation classes and back. The NSData are basically strings that haven't been decoded with any locale convention. See for example raywenderlich.com/5492/working-with-json-in-ios-5 to see how all this fits together. Commented Apr 21, 2013 at 17:44

1 Answer 1

18

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Because to_json returns a string, so quotes are escaped. as_json returns a hash.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.