Root
Root

Reputation: 2361

Convert [object Object] to JSON

I have to pass some params from js to rails. And because the params are too long, I have to use post method and make the params be JSON, not string. But I can't change the parts back to JSON in rails.

<ActionController::Parameters {" "=>nil, "test"=>"[object Object]", "controller"=>"super", "action"=>"addArticle"} permitted: false>

And I want to get the params in parms[:test] [sic]. But I can only get this:

params[:test]
#=> [object Object]

So, please help me.

Upvotes: 0

Views: 2461

Answers (1)

Vaibhav
Vaibhav

Reputation: 658

I think you are passing the object like so in your call

$.ajax.post('/to/some/url', data: { test: js_object } );

where test is something like { "some" : "value" }.

What you need to do is to first stringify the object. Something like this should do:

$.ajax.post('/to/some/url', data: { test: JSON.stringify(js_object) } );

When you send objects directly, they are converted to a string by JavaScript and when JS converts an object to string automatically, it converts it into [object Object].

To prove, just run the these lines in console one after another:

console.log({a:'b'});
console.log({a:'b'}.toString());
console.log(JSON.stringify({a:'b'}));

You will figure out the difference!

Upvotes: 4

Related Questions