开发者

Error parsing JSON: undefined method 'gsub'

开发者 https://www.devze.com 2023-03-04 04:47 出处:网络
I\'m trying to parse JSON in JavaScript, but I\'m getting this error in Rails: undefined method `gsub\' for #<Array:0开发者_开发问答x000001054a2440>

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

精彩评论

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