Search code examples
ruby-on-railsrubyjsonapiline-breaks

ruby json new line break rendered format incorrectly


i tried to rendor json format in ruby on rails

My code:(ruby code)

:address=> 'Address:\nshollinganallur,\nchennai.'

Rendered json output:

"address": "Address:\\nshollinganallur,\\nchennai."

I tried with old questions and answer. but nothing happend. Any help?


Solution

  • There are no newlines in this:

    :address=> 'Address:\nshollinganallur,\nchennai.'
    

    The \n escape sequence doesn't work in single quoted strings so you're just getting the two characters \ and n.

    When that's converted to JSON, the \ has a meaning so it has to be escaped with another \. Hence the output you're seeing.

    If you start with:

    :address => "Address:\nshollinganallur,\nchennai."
    

    then you'll get your newlines all the way through.