Thursday, September 07, 2006

JSON Reader

Today is a boring day, I decided to create a lightweight JSON reader for JSON manipulation using JavaScript (After I have not been touching JSON and JavaScript prototype since my FYP). My intention of creating this JSONReader is simply to manipulate/read the JSON value with string path supplied. To start off, I use a very simple JSON in my example.

var myJSON = {"Image": {
"Width":800,
"Width":200,
"Height":600,
"Title":"View from 15th Floor",
"Thumbnail":
{
"Url":"http:\/\/scd.mm-b1.yimg.com\/image\/481989943",
"Height": 125,
"Width": "100"
},
"IDs":[ 116, 943, 234, 38793 ]
}}


Now, we "instantiate" the object of JSONReader with the JSON format passed as parameter to its constructor.


var reader = new JSONReader(myJSON);


Then at the frontend, we allow the users to key in the string path in the TextBox.


<input type="text" id="txtPath" name="textfield">
<input type="button" onclick="GetValue()" name="Submit" value="Get the Value">

<span id="lblMessage"/>


The string path provided by user will be passed to the FindValueByKeyPath() method of JSONReader in the GetValue() function to obtain the value in JSON. The $F() is the method in the prototype.js that used to retrieve the value of specified HTML element.

var path = $F("txtPath");
lblMessage.innerHTML = reader.findValueByKeyPath(path);


Test Results
User Input : Image\Thumbnail
Output : {"Url":"http://scd.mm-b1.yimg.com/image/481989943","Height":125,"Width":"100"}

User Input : Image\Thumbnail\Url
Output : http://scd.mm-b1.yimg.com/image/481989943


Screenshot



Additional Libraries Needed
prototype.js
$F(), class.Create()

json.js
parseJSON(), toJSONString()


The complete example can be downloaded here


Still boring ~~ :|

No comments: