Friday, April 19, 2013

JSON in 5 minutes


JSON = JavaScript Object Notation

  • lightweight data-interchange format
  • is literally javascript code - valid data types: Objects, Arrays, Numbers, Strings (includes Date), Boolean
  • keys must be in quotes, unlike in javascript code the keys do not need quotes.
  • Supports unlimited nesting 

Example

 {
 "key1": "I like cheese",
 "key2": ["An","array","of","strings","with",1,"number"],
 "keyForAnObject": {
   "Cheeses": ["Blue","Swiss","Cheddar","Jack"],
   "NumberOfCheese": 2,
   "FavoriteCheeseIndex": 1,
   "isThereAFavorite": true
 }
}
Accessing the data in Javascript:
var JsonDataString = {
 "key1": "I like cheese",
 "key2": ["An","array","of","strings","with",1,"number"],
 "keyForAnObject": {
   "Cheeses": ["Blue","Swiss","Cheddar","Jack"],
   "NumberOfCheese": 2,
   "FavoriteCheeseIndex": 1,
   "isThereAFavorite": true
 }
};

var data = JSON.parse(JsonDataString); // JSON is a global function

data.key1 // "I like cheese"
data.key2[3] // "strings"
data.key2[5] // 1
var internalObject = data.KeyForAnObject;
internalObject.Cheeses[1] // "Swiss"
data.KeyForAnObject.Cheeses[1] // "Swiss"

Most important Javascript JSON functions

JSON.parse( JsonDataString )
Safer than eval(). Returns a javascript object/type.
JSON.stringify( Object )
Returns a JSON string from any non-function javascript object. 

Cross platform

These Javascript JSON functions are available in some form for basically every programming language.
See http://json.org/ and scroll down for all of the supported libraries. 
Note: JSON.stringify() is often "serializeAsJson" or something similar.

C# Pseudo-code Example

using System.Web.Script.Serialization;
class SomeClass
{
 class JsonResponse
 {
  public bool TrueOrFalse = true;
  public string Hi = "hi!";
  public List = new List();
 }
 
 public static string Responder()
 {
  JavaScriptSerializer jss = new JavaScriptSerializer();
  JsonResponse resObj = new JsonResponse();
  
  return jss.Serialize(resObj);
 }
 
}

Use cases

JSON can be used wherever XML is used, but is more human readable and has a smaller footprint. More easily supports typed data than XML.
Returning JSON from a server to a client browser during AJAX. Since JSON maps directly to a javascript object it can be manipulated as native code.
Multidimensional arrays or arrays of objects are common, representing database rows and columns.
Example response from server:
Content-Type: application/json
[[
 1,"Jim","yeeee"
],[
 2,"Wilson","I like cheese"
]]

as XML, it might look like:

 
  1
  Jim
  yeeee
 
 
  2
  Wilson
  I like cheese
 


No comments:

Post a Comment