0

I need to convert an string to hash so that i can use its "id" attribute. I am getting this string due to following code in my .js.erb file:

$('#link_id').data('test', "<%= @record_obj.as_json %>");

I am getting string in following format:

"{&quot;id&quot;=&gt;166,&quot;first_name&quot;=&gt;James}"

I need to convert above string to hash so that i can access "id" of the object.

Any help will be appreciated. Thanks :)

3 Answers 3

1

Add 'raw' to get a clean output when using erb inside of javascript.

$('#link_id').data('test', JSON.parse(<%= raw @record_obj.as_json %>));
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for the help. Now i do not need to replace the &quot;. I am getting it as "{"id"=>189, "first_name"=>"James"}, but as a string instead of hash. Could you please help me out over here?
I have updated the answer. The reason you are getting a string is because you had wrapped your @record_object in quotes $('#link_id').data('test', "<%= @record_obj.as_json %>"); I removed them and now you should get your raw JSON. Please upvote and mark correct if deemed correct!
If i am not wrapping it in quotes its blocking my js.erb logic.
$('#link_id').data('test', JSON.parse(<%= raw @record_obj.as_json %>)); This will convert the JSON to a Javascript object, which should enable you to iterate through it.
Thanks a lot friend. It is working. :) But i need to change as_json to to_json. Does that really matters?
|
0

Try use id directly

$('#link_id').data('test', "<%= @record_obj.id %>")

1 Comment

thanks for the reply. But i need the entire record instead of only id. Only for now i need to access "id".
0

try

$('#link_id').data('test', <%= @record_obj.as_json.html_safe %>);

1 Comment

Thanks for your answer. I tried it, but got the error of in valid method 'html_safe'.

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.