Ruby/Rails - 如何防止字符转义(或之后取消转义)?
我有一些 json 位于已转义的文本文件中:"{\"hey\":\"there\"}"
当我尝试读取文件时:File.open("\file\path.txt").read
它再次转义内容,因此现在是双重转义的:"\"{\\\"hey\\\":\\\"there\\\"}\""
有办法防止转义吗?
或者,在读取并转义字符串后,是否有一种简单的方法可以对字符串进行转义?
谢谢。
编辑:
答案很有道理,但我似乎无法解析 JSON。
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\"}"
'
意想不到的令牌在哪里?
谢谢。
编辑2:
“问题是你的文件可能是有效的 JS,但它不是有效的 JSON,所以 JSON 库往往会拒绝它。”
我信任消息来源(我),所以如果我运行:x = JSON.parse(eval(json))
它有效!
谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
试试这个:
编辑:
IRB 的输出:
如果您仍然希望它是一个字符串:
Try this:
Edit:
Output from IRB:
And if you still want it to be a string:
事实并非如此。它只是以这种方式显示,但如果你尝试计算反斜杠,你会发现该字符串与文件中的相同:
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: