Interesting Issue with eval() and JavaScript JSON
I was enhancing my web app today based on a request that someone voiced about making it easier to have a user see everything all the time. Face it, there are a good chunk of users that are in the Risk Management group that are going to need to see everything all the time. If I made a permissioning scheme based on an enumerated list, then when I added a new portfolio, I'd have to update these users. Sort of a hassle.
So the request was to have a wildcard for the portfolio list, and when a user had this, they would be able to see all portfolios regardless of how many there were. It's a good idea, I just hadn't thought of it.
But that's not the issue.
What I realized was that there were likely going to be a lot more changes to the permissioning scheme, and in that case, my semi-colon-delimited list of values was not going to do. What I needed was to be able to pass in a fully created JavaScript object and then let the page be able to interrogate it as necessary.
For example, if my validation applet was given a parameter out of json then it might return the following JSON output:
{ username: 'beatyr', page: 'PnLTool', approved: true, portfolios: ['Indexes', 'Nasdaq'] }
then when parsed, I should be able to say things like:
if (!userInfo.approved) { }
Nice.
All this seems well and good, and I should be able to simply say:
var userInfo = eval(xhr.responseText);
but that won't work. Why? The fact lies in the interpretation of the initial '{' in the string value. The parser in eval() thinks it's the start of a block of code, not a JSON value, so you have to force eval() to get into object evaluation mode by wrapping the JSON in '()'. Like:
var userInfo = eval('(' + xhr.responseText + ')');
When you put this into the script, it works like a charm. Perfectly understandable from the point of eval(), but a little tricky if you forget about it.