Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Wednesday, January 8, 2014

Parsing Imperfect JSON

In JavaScript, each JSON attribute name should be wrapped in quotes for it to be parsed correctly. Sometimes you may receive a JSON string that isn't properly formed because of the missing quotes. You can still parse it using the technique described below.

To start, here's an example of malformed JSON using JSON.parse and jQuery's $.parseJSON. You'll notice that it doesn't parse the JSON string since it doesn't have its names wrapped with quotes.
//Using native JS: JSON.parse
//Similar result for jQuery $.parseJSON
var jsonStr = '{ename : "martin", sal: 100}';
var jsonObj = JSON.parse(jsonStr);

//Raises error: 
SyntaxError: JSON.parse: expected property name or '}'


//Correct JSON object (notice attribute names are quoted)
var jsonStr = '{"ename" : "martin", "sal": 100}';
var jsonObj = JSON.parse(jsonStr);
console.log (jsonObj);

//Returns JSON object
Object { ename="martin", sal=100}
To get around this issue you can use JavaSript's eval method. It's not pretty but it does the job and will probably save you a lot of time trying to correct your JSON object.
var jsonStr = '{ename : "martin", sal: 100}';
eval('jsonObj = ' + jsonStr + ';'); 
console.log(jsonObj);

//Returns JSON object
Object { ename="martin", sal=100}
I've found this technique really helpful when passing back JSON strings from APEX AJAX calls (via a Dynamic Action, Plugin, or custom AJAX).

Update: Please read John's comment below as he makes a good point that the data should be data that you control otherwise perfect area for a JS injection attack.

Sunday, January 30, 2011

Console Wrapper (previously JS Logger)

I've moved the Console Wrapper (previous called JS Logger) code to be hosted as a Google project here: http://code.google.com/p/js-console-wrapper/

I decided to create a Google project since maintaining code via a blog is not the best or easiest thing to do. I will continue to blog about any major updates but all examples, documentation, issues, and code will be maintained on the Google project page.

Previous references to Console Wrapper
- http://www.talkapex.com/2010/08/javascript-console-logger.html
- http://www.talkapex.com/2011/01/js-logger-101-logparams.html

Monday, January 17, 2011

JS Logger 1.0.1 - logParams

Note: This now has a new name, Console Wrapper, and has been moved to a Google project. Please go to http://www.talkapex.com/2011/01/console-wrapper-previously-js-logger.html for more information.

I've updated my JavaScript Console Logger package to include a new function called logParams. logParams will automatically log all the parameters in your function. This can save a lot of time since you don't need to manually list all the parameters and it will detect any "extra" parameters.

Here's an example of the code:
function myFn(px, py, pz){
  $.console.logParams();
  
  //do something as part of this function
  
}//myFn;

//Not required if using in APEX. 
//If called from APEX it will detect if you are in debug mode
$.console.setLevel('log'); 

//Call myFn with the correct amount of parameters
myFn(1,2,3);

//Call myFn with more than "expected" number of parameters
myFn(1,2,3,'hello', 'goodbye');
Which results in:

Note: by default the parameters groups are collapsed by I've expanded them for this demo

Download Javascript Console Logger $logger.1.0.1. For more information about this javascript library please read my original post: http://www.talkapex.com/2010/08/javascript-console-logger.html

Thanks to Dan McGhan for helping come up with this idea.

Monday, August 30, 2010

JavaScript Console Logger

Note: This now has a new name, Console Wrapper, and has been moved to a Google project. Please go to http://www.talkapex.com/2011/01/console-wrapper-previously-js-logger.html for more information.

If you've been developing APEX applications for while, or any web applications for that matter, you'll eventually leverage the browser console. If you've used Firebug, then you've had the console accessible to you.

In case you're not sure what console is, it allows you to display debug information in a nice console window within your browsers. Most (i.e. all browsers but IE) are console enabled. The most common use of console is the console.log command:
console.log('hello world');

Console has a lot of great features. One drawback with it is that you have to remove calls to console before putting your code into production since not all browsers support console.

Removing instrumentation code before going into production can be annoying, especially if you need to debug it later on. To resolve this issue I've created a console wrapper. This allows you to leave your debugging calls in production code. Here are some features:

  • Works in all browsers. If run in IE nothing will happen, but no error message.

  • Allows you to set Levels. By default no messages will appear.

  • Support for jQuery chaining (see examples).

  • Will automatically set level to "log" if run in APEX and APEX is in Debug mode.

A copy of the console wrapper is available here: Download $logger_1.0.0.

The only change that you'll need to make is call $.console instead of console. The download file includes a HTML file with demos. I'd recommend looking at the .js file as well for inline documentation.

Here's an example along with its output:
$.console.setLevel('log');
$.console.log('Current Level', $.console.getLevel());
$.console.group('Available Levels');
$.each($.console.levels, function(i, val){
   $.console.log(i);
});
$.console.groupEnd();
$.console.log(($.console.isApexDebug()) ? 'In APEX debug mode' : 'Not in APEX debug mode');
$.console.group('Demo Chaining');
//Notice how you can write this out all in 1 line!
$('.red').log('Before Red').css({color:'red'}).log('After Red');
$.console.groupEnd();
$.console.info('Turning off console');
$.console.setLevel('off');


For more information about console please read the following articles:

- Console APIs: http://getfirebug.com/wiki/index.php/Console_API
- Firebug console example: http://getfirebug.com/logging
- Console tutorial: http://www.tuttoaster.com/learning-javascript-and-dom-with-console/

Monday, July 20, 2009

JavaScript: ? = If Else

This is not directly related to APEX however it will help if you use a lot of JavaScript

When I first started to develop web based applications and used JavaScript I came across some JS code with a ? in it. I didn't know what it was for and Googling "JavaScript ?" didn't help either. Here's a quick summary on how it works

Boolean ? true action : false action

So this:

var x = 2;
if (x > 1)
window.alert('True');
else
window.alert('False');


Becomes this:

var x = 2;
x>1 ? window.alert('True') : window.alert('False') ;