Eval not working within Rest Resource JavaScript asset


(M L Sanders) #1

Hi All

I've successfully retrieved JSON data from an authenticated (OAuth2) source.

 

I'm using a RestResource JavaScript page in an attempt to parse/format/display....

 

When I simply display the JSON using 'print (_REST.response.body);' everything is good - I get JSON on screen.

 

However, using eval (as suggested in the manual) or JSON.parse doesn't work. The following code:

 

var status = eval('(' + _REST.response.body + ')');

print (status.length);

print (status);

 

displays: undefined [object Object].

 

Using JSON.parse is worse - everyting after the call breaks (nothing printed). 

 

So I can't parse the JSON and therefore can't start to do anything with it.

 

Any idea what's going wrong here?

 

 

thanks

mark


(Marcus Fong) #2

What’s “JS Engine” set to in your REST Resource JavaScript asset - “v8js” or “SpiderMonkey”?


(M L Sanders) #3

Hi Marcus

It's set to SpiderMonkey - but I don't know where to check whether it's installed or not!!!

I know that some things (the print statement, for example) work....


(Marcus Fong) #4

It’s possible that you’ve got an older version of SpiderMonkey that doesn’t support JSON.parse().

You could try switching to v8js, which - assuming it’s installed - should always have JSON.parse() available.


(Nick Papadatos) #5

Can you clarify if the library (SpiderMonkey) has been installed on the server by your sysadmin?


(Gilles Olivier Guegan 1) #6

Hi Mark,

 

To see if the issue is with your version of the JS engine (whichever you're using), you could include something like Crockford's JSON parse to your rest asset:

 

https://github.com/douglascrockford/JSON-js

 

It might solve your issue if you have an older version of the JS engines installed and can't upgrade them.

 

Also, your eval seems to be working properly. I believe in this context eval will return an object, which doesn't have a length property, so status.length will return undefined.

 

And print(status) won't print the actual content of the js object, not like it would a string, but just return the "type of" what you're trying to print, so in this case, "[object Object]".


(M L Sanders) #7

Oops; should have updated this with the outcome: we did exactly that: added the json_parse.js script to the asset.

 

It may also be of interest to know that the page had a 'general' design attached - this was (ever so slightly) mangling the JSON which wasn't parsed correctly.

When the design was altered to serve the content as JSON, the parsing succeeded.....but we did need the json_parse to be added manually.

 

thanks Gilles, Nicky and Marcus