Thursday, May 26, 2011

My Latestest infatuation with JSON - JavaScript Object Notation

We've MOVED!!!! www.codeboxllc.com/ksc

I'm in love with JSON, JavaScript Object Notation. It's old news, I know this and I'm not that proud of it. But wise man once said, "It's better late than never". I'm currently addicted to using it. I am starting to go back to all NetSuite scripts I've created to this date and seeing where I can incorporate JSON.

I first used it when I worked on workaround for NetSuite Webstore Registration Process. The online Suitelet returns a JSON object which contains the result of search. I've started using it since.

I started using JSON as Mapping Table. I used JavaScript Arrays to store list of values and get them out but as you know, it's very inefficient. I also used JavaScript Objects as well to store attributes.

JavaScript Object to store Address info:
var addr1=new Object();
addr1.label='Company Address';
addr1.add1='1234 Hello World';
addr1.add2='#303';
addr1.city='My City';
addr1.state='My State';
addr1.zip='99999';
//second address
var addr2=new Object();
addr2.label='Home Address';
addr2.add1='999 Home World';
addr2.add2='';
addr2.city='My City';
addr2.state='My State';
addr2.zip='44444';


document.write(addr1.label);
//This will write out Company Address on the screen
document.write(addr2.label);
//This will write out Home Address on the screen
JSON to store Address info:
var addr={
  "CompanyAddress": {
    "label":"Company Address",
    "add1":"1234 Hello World",
    "add2":"#303",
    "city":"My City",
    "state":"My State",
    "zip":"99999"
  },
  "HomeAddress": {
    "label":"Home Address",
    "add1":"999 Home World",
    "add2":"",
    "city":"My City",
    "state":"My State",
    "zip":"44444"
  }
}


document.write(addr['CompanyAddress'].label);
//This will write out Company Address on the screen
document.write(addr['HomeAddress'].label);
//This will write out Home Address on the screen
What I like about using JSON approach is that it is already treated as an Array. Array with unique id. I can also have Server side Suitelet to generate something like this and use eval(); to parse it as JSON.

Take this as an example. Let's say someone registered from your website and provided series of addresses. If you have know exactly what you are looking for, you don't have to run a loop to find the right address. You can simply reference unique ID you gave and get related attributes for it just like above.

You can also run loop against your JSON object by doing this:
for (_v in myJsonObj) {
  document.write(myJsonObj[_v].attribute);
}
//above will loop through all elements in myJsonObj and print out value for attribute
Anyway, pretty simple yet powerful. Love LOVE using it!!!

No comments:

Post a Comment