1

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 message. The problem is with ";" character.

Which could be the error?

5
  • what is producing the &quot version? Commented Oct 4, 2011 at 18:16
  • @jaydel I am using rails so I convert to json inside a jQuery function. Now i edit and post the js function. Commented Oct 4, 2011 at 18:23
  • How about using CGI.unescapeHTML instead of gsub? Commented Oct 4, 2011 at 18:29
  • @Nick are the master of code. Thank you very much. Commented Oct 4, 2011 at 18:35
  • @user751132 Please accept an answer if it meets your needs. Commented Oct 5, 2011 at 12:56

2 Answers 2

1

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

JSON.parse(CGI.unescapeHTML(params[:contacts]))
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.