开发者

Error parsing JSON: undefined method 'gsub'

I'm trying to parse JSON in JavaScript, but I'm getting this error in Rails:

undefined method `gsub' for #<Array:0开发者_开发问答x000001054a2440>

my code is as follows:

<script type="text/javascript">
  var stuff = <%= escape_javascript(@json) %>
  var json = stuff.parseJSON();
  alert("text");
</script>

where @json is defined in the controller as @nodes.to_json

Can someone please help me with this? Getting JSON to JavaScript shouldn't be hard, but it's taking me forever.


The code for escape_javascript is:

def escape_javascript(javascript)
  if javascript
    javascript.gsub(/(\\|<\/|\r\n|[\n\r"'])/) { JS_ESCAPE_MAP[$1] }
  else
    ''
  end
end

Thus, I would conclude that @json is actually an Array.


you are applying gsub methods for array that's why undefined method `gsub' for # occur. @json is array and you cant apply gsub on it.


use JSON.parse if natively available or else include a json parser, the most popular one is written by Douglas Crockford

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜