A JS(ON) Oddity

Been running into a weird buggish issue. I have a method that basically builds a big JSON object, field by field, then returns it. It worked when I test it in console.

Once provisioned, however, I got a strange “Unable to convert Javascript object to string” error. I’m assuming that somewhere during execution, the JSON string was interpreted as a JS object (although I made sure that fields were defined with strings, e.g. { ‘field’: ‘value’ } not { field: ‘value’ } or field.value). I was able to deduce that the error was actually triggered when the function returned–everything up to that point still worked fine.

I was able to fix this by enclosing the return value in JSON.stringify(). Any ideas what went wrong?

tl;dr Why did wrapping my JSON object in stringify() fix an “Unable to convert Javascript object to string” error?

To not be interpreted as JS object, the entire JSON string needs to be wrapped with quotes; i.e. instead of
{ 'field': 'value' }
it should be
"{ 'field': 'value' }"
or even better
'{ "field": "value" }'
since JSON spec specifies double quotes: https://www.json.org/

It was a little unclear in your post whether you did that or not.

1 Like

Gotcha, looks like I got that wrong. Thanks for clearing that up.