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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With