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.
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: