Trimming values from JSON objects
My current work is really focused on Ajax and JSON, and I get a lot of different things done that might be of use to others.
Today I’ve come up with a neat little function for trimming a JSON object given an array of all values to trim out. The trim function recursively runs though the JSON object and deletes all occurences of the specified values. Optionally, any present or resulting empty objects within the provided JSON object can also be deleted in the process.
My function has this form:
function jsonTrim( json, trimValuesAry, bDeleteEmptyObjects )
The first parameter json is the JSON object to trim, and also the resulting object.
The second parameter trimValuesAry is an array of values to trim out, e.g. [ "", null ]. Do note that objects are not treated by jsonTrim as values but as begin part of the data-structure. Therefore you can only specify leaf-values in trimValuesAry that can occur within objects as key/value pairs.
Finally bDeleteEmptyObjects is an optional bool parameter, it may be omitted. The default value if omitted is false. If set to true any present or resulting empty objects are also deleted.
Trimming json = { obj: { string: “foo” }, bar: 42, nil: null } with [ "foo", null ] and requesting empty objects to be deleted would result in json = { bar: 42 }:

Download (right-click and choose “Save as…”)
jsonTrim.js version 0.1.
jsonTrim-jsmin.js version 0.1 (JSMinified).
jsonTrim-v0.1.zip version 0.1 (zip archive containing all files incl. test).
Test (demo):
jsonTrim-Test.htm.
jsonTrim-jsmin-Test.htm.
License:
Creative Commons GNU LGPL.
Revision history:
2008-01-29, 22:37:
v0.1 first release.

Converting
