JSONLib: JSON Extensions a la E4X
Date : 2008 01 18 Category : Tech & DevelopmentNicholas C. Zakas wanted to keep JSON out of JavaScript. He has patterned a new form of JSON support on E4X and wrote it up.
Nichole wants:
The addition of two new global types: JSON and JSONList. JSON represents a JSON object while JSONList represents a JSON array. Both types have a toJSONString() method that correctly encodes an object into a JSON string. The default toString() method is available but returns a string representation of the object (not a JSON string). This follows the convention set forth in E4X. The [[Put]] method is overridden in both types such that it will only accept values of type JSON, JSONList, Date, boolean, string, number, or null. Any other data types cause an error to be thrown. The JSON constructor allows an object to be passed in that has initial properties to add; the JSONList constructor allows an array to be passed in with items to add. The typeof operator should return "json" when used on a value of type JSON or JSONList. JSON strings are parsed via JSON.parse(), throwing syntax errors if they are found.You can see it in action:
PLAIN TEXT JAVASCRIPT:var obj = JSON.parse("{"name":"Nicholas","age":29}"); var json = new JSON(); json.put("name", "Nicholas"); json.put("age", 29); var name = json.get("name"); var str = json.toJSONString(); var list = new JSONList(); list.put(0, "blah"); list.push(25); list.push(true); var val = list.get(1); var len = list.getLength(); var str = list.toJSONString(); var json = new JSON({name:"Nicholas"}); var name = json.get("name");
Summary
It is slightly more verbose than the current methods for using JSON in JavaScript, however, I believe this solution keeps JSON out of the core of JavaScript and maintains useful access to JSON parsing and serialization. The key to understanding this approach is that JSON and JSONList are purely data storage objects without any additional functionality. They have one job and they do it well. Make sure you only use put() or other methods to add values to the objects instead of just assigning new properties.