Official ObjectGraph Blog

Tuesday, November 21, 2006

JSON - Serialized Language and Cross-Domain Scripting

Installation

In .NET This is nice stand-alone library for .NET environment http://www.newtonsoft.com/products/json/quickstart.aspx

  1. Right click on project
  2. Add Reference
  3. Browse Newtonsoft.Json.dll

In PHP JSON library is ready as extension of apache.

  1. Download php_json.dll http://www.aurore.net/projects/php-json/
  2. Copy php_json.dll in ext directory
  3. Modify php.ini (Add extension=php_json.dll)
  4. Restart Apache

Description

What is JSON? JSON is just serialization language. That means you convert your class or array in PHP, Java, .NET, etc... into JavaScript, so that you can pass the data around between different platform. Since the data object is already in JavaScript, it makes AJAX guys happy. Somebody claims JSON as "Light-weight version of XML". Because you do not parse it.

As for cross-site scripting, it's nothing to do with JSON. But I explore the advantages of the combination.

The first example demonstrates JSON object's serialization/deserialization in PHP language. I just encode array into JSON, and the other section decode from JSON. As you see, you can put these parts in remote server. This client can be another plat form.

The second example is ASP.NET example is code to demonstrate how to achive cross-domain data transfer. Basic model is like this

  1. ASP.NET spit out JavaScript library which returns a JSON object. The JSON object is just serialized string array object.
  2. In html page, javascript include the aspx page as library, and call the function to obtain JSON object. The object is just array of string in javascript.

Service / Client Test in PHP

1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr);
echo '<hr />';
?>


Building JSON Service - JSONTest.cs File

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Newtonsoft.Json;

public partial class JSONTest : System.Web.UI.Page {
public string mOutput;
protected void Page_Load(object sender, EventArgs e) {
string[] arr = new string[] { "apple","banana","orange","strawberry" };
mOutput = JavaScriptConvert.SerializeObject(arr);
//Response.Write(mOutput);

}
}

Building JSON Service - JSONTest.aspx Page

This is assumed to be used as .js library. getObj return parsed JSON object.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="JSONTest.aspx.cs" Inherits="JSONTest" %>
// You do not need to wrap in JS function if you use in another language like PHP, Python, etc...
function getObj() {
return eval('(<%=mOutput %>)');
//return eval('(["apple","banana","orange","strawberry"])');
}

Consuming JSON in JavaScript





<script type="text/javascript" src="http://%28aspx%20page%20location%29/JSONTest.aspx"></script>
<script language="javascript" type="text/javascript">
var obj = getObj();
document.write(obj[0] + "<br />");
document.write(obj[1] + "<br />");
document.write(obj[2] + "<br />");
document.write(obj[3] + "<br />");
</script>

posted by Kiichi Takeuchi at 3:58 PM | 1 comments |

Saturday, November 18, 2006

Beautiful Soup
The Python HTTPParser both in HTTPParser and htmllib are very flexible to provide your own implementations for handling start tag, end tags and data elements, but it has limitations. For example if i wanted to preserve input formatting of HTML, but change just a few tags it would be hard to do.

I found a better solution.

Beautiful Soup is a good HTML parser from the initial impressions. I tried many public sites like cnn.com, news.com etc and able to parse it into a tree and access the elements very easily.

It provides very easy functions to search the entire tree and returns references to those.

Lets say, you want to get all hyperlink (a) tags, the code would be as simple as below

from BeautifulSoup import BeautifulSoup
import urllib2;

data=urllib2.urlopen("http://www.cnn.com")
soup=BeautifulSoup(data.read())

resultset=soup.findAll("a")
for i in range(len(resultset)):
 print resultset[i]

Now say, you want to make all the links absolute instead of relative, a simple function that takes the resultset would do the trick


from BeautifulSoup import BeautifulSoup
import urllib2

def relativetoabsolute(resultset,tag,url):
  for i in range(len(resultset)):
      try:
          link=str(resultset[i][tag])
          if not link.lower().startswith("http"):
              s[i][tag]=urljoin(url,link)
      except:
          pass

data=urllib2.urlopen("http://www.cnn.com")
soup=BeautifulSoup(data.read())

resultset=soup.findAll("a")
relativetoabsolute(resultset,'href','http://www.cnn.com')
print soup


The output HTML would have all relative URLs while preserving input formatting. The cool thing is you could prettify the output by just
print soup.prettify()

posted by gavi at 8:52 PM | 2 comments |

Wednesday, November 15, 2006

Python Tutorial
Everyone at OG is learning Python and related web frameworks (Django, TurboGears etc). I will be posting which one is better soon, but in the mean time we have a python tutorial on our wiki. Python Tutorial Most of the code is from Prof. Devi Murali's course on python @ Long Island University. I added some of my examples and descriptions to the examples. You can see Devi's website here.

posted by gavi at 12:40 PM | 0 comments |

Tuesday, November 14, 2006

Google's Start Page
Google Apps for your Domain has a new portal app called "startpage" I tried it and here is the result. http://portal.objectgraph.com I remember the time when companies were being sold Portal products (Portlets etc) for a lot of dough and only the big companies could afford them. Now any small business could have their own customized portal. I still think LDAP access needs to be opened up from Google, so local data could be easily integrated via this portal.

posted by gavi at 2:22 PM | 0 comments |

Wednesday, November 01, 2006

Cool Commenting System
Check this commenting system

http://www.djangobook.com/en/beta/
You can comment on any section of the page. Its based on Yahoo UI.
http://developer.yahoo.com/yui/

posted by gavi at 12:51 PM | 1 comments |

Google Apps for Your Domain and LDAP
I have been using Google Apps for Your Domain from the initial test phases and one thing I always wanted was LDAP access to the accounts we create on Google. This will enable us to build additional services internally leveraging Google's account management. This additional feature will make single signon a possibility

posted by gavi at 10:48 AM | 0 comments |