Ruby on Rails JSON.parse 意外令牌错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5130822/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ruby on Rails JSON.parse unexpected token error
提问by SZH
I am trying to parse JSON data in my Rails 3 application with JSON.parse. I keep getting this error:
我试图在我的 Rails 3 应用程序中解析 JSON 数据JSON.parse。我不断收到此错误:
737: unexpected token at '{\"0\":{\"class\":\"window\",\"text\":\"Testing\",\"style\":\"position: absolute; top: 8px; left: 8px; width: 560px; height: 290px; z-index: 0; \"}
737:'{\"0\":{\"class\":\"window\",\"text\":\"Testing\",\"style\":\"position: absolute; 处的意外标记;顶部:8px;左侧:8px;宽度:560px;高度:290px;z-index:0;\"}
The actual JSON is a lot longer, but it is basically the same.
实际的JSON要长很多,但基本上是一样的。
回答by Michelle Tilley
Well, we can only answer based on the part of the JSON you showed us, but it has two problems:
好吧,我们只能根据您展示给我们的 JSON 部分来回答,但是它有两个问题:
- All the quote characters (
") are escaped; they don't need to be unless they are used in a double-qoted string, which it appears they are not. - You are missing a closing brace (
}).
- 所有引号字符 (
") 都被转义;它们不需要,除非它们被用在双引号字符串中,看起来它们不是。 - 您缺少右大括号 (
})。
Otherwise it passes based on https://jsonlint.com/.
否则它会基于https://jsonlint.com/传递。
回答by Pratik Khadloya
In my case it was a hidden tab character which showed up only when i pasted it into vim.
就我而言,它是一个隐藏的制表符,仅在我将其粘贴到 vim 中时才会显示。
回答by Jai Kumar Rajput
You can directly use JSON.Parse()in-build method:
您可以直接使用JSON.Parse()in-build 方法:
content = "[{\"addon_id\":\"1\",\"addon_price\":\"5\"}]"
# OUTPUT at Console => "[{\"addon_id\":\"1\",\"addon_price\":\"5\"}]"
JSON.parse(content.gsub('\"', '"'))
# OUTPUT at Console => [{"addon_id"=>"1", "addon_price"=>"5"}]

