开发者

Error while parse a json object as ruby object

My question is the next:

When i try parse a json params with 'json' gem on RUBY ON RAILS 3 throw this error:

 Unexpected token at 

Example

I have this object in ruby:

Then I have this html code:

<script>
        $("#selected").live('click', function(){
            jQuery.ajax({url: '<%= deselect_all_checkboxes_path %>', data: {contacts: '<%= contacts.to_json %>'}});
        });
</script>

<input type="checkbox" id="selected" value="1" >

I try this code in Rails Console

JSON.parse(json_string.gsub(/&quot;/, "\"")) 

Works ok. However when i try this code:

JSON.parse(params[:contacts].gsub(/&quot;/, "\"")) 

There is a problem in the gsub method. In Rails Console works ok but when i am debugging throw the error 开发者_如何学JAVAmessage. The problem is with ";" character.

Which could be the error?


Unescape the HTML first and then parse it as straight JSON:

JSON.parse(CGI.unescapeHTML(params[:contacts]))


You don't want to quote your contacts.to_json value inside your jQuery, that turns it into a string when you want it to be a JavaScript object literal; once your data is a string, it will end up HTML encoded by ERB and you get the mess you're seeing. Try this in your jQuery:

data: {contacts: <%= contacts.to_json.html_safe %>}

That should get you a nice JavaScript object literal in your jQuery and that will be serialized into a JSON object (rather than a JSON string) when it is sent back to your server.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜