Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby/Rails - How do I prevent character escaping (or unescape afterwards)?

Tags:

ruby

escaping

I have some json that is in a text file that has already been escaped:
"{\"hey\":\"there\"}"

When I try to read the file:
File.open("\file\path.txt").read
It escapes the contents again, so that it is now double-escaped:
"\"{\\\"hey\\\":\\\"there\\\"}\""

Is there a way to prevent the escaping?
Or, is there an easy way to unescape the string after it's been read and escaped?

Thanks.

EDIT:
The answers make sense, but I can't seem to parse the JSON anyway.

irb(main):018:0> json
=> "\"{\\\"hey\\\":\\\"there\\\"}\"\n"  


irb(main):019:0> puts json  
"{\"hey\":\"there\"}"  
=> nil 


irb(main):017:0> x = JSON.parse(json)  
JSON::ParserError: 751: unexpected token at '"{\"hey\":\"there\"}"  
'

Where's the unexpected token?

Thanks.

EDIT 2:

This SO question had the answer

"The problem is that your file might be valid JS, but it isn't valid JSON, so JSON libraries tend to reject it."

I trust the source (me), so if I run:
x = JSON.parse(eval(json))

it works!

Thanks.

like image 208
johnnycakes Avatar asked Jan 31 '12 15:01

johnnycakes


2 Answers

Try this:

require 'json'
JSON.parse(File.read("\file\path.txt"))

Edit:

Output from IRB:

1.9.3p0 :006 > json = JSON.parse("{\"hey\":\"there\"}")
=> {"hey"=>"there"}

And if you still want it to be a string:

1.9.3p0 :007 > json = JSON.parse("{\"hey\":\"there\"}").to_s
1.9.3p0 :008 > puts json
{"hey"=>"there"}
=> nil
like image 144
Eugene Avatar answered Oct 13 '22 17:10

Eugene


It escapes the contents again, so that it is now double-escaped:

It doesn't really. It's only displayed this way, but if you try to count backslashes, you'll find out that string is the same as in file:

ineu@ineu ~ % cat > 1.txt
"{\"hey\":\"there\"}"
ineu@ineu ~ % pry
[1] pry(main)> a = File.open('1.txt').read
=> "\"{\\\"hey\\\":\\\"there\\\"}\"\n"
[2] pry(main)> puts a
"{\"hey\":\"there\"}"
=> nil
[3] pry(main)> a.count '\\'
=> 4
like image 29
Ineu Avatar answered Oct 13 '22 17:10

Ineu