Created
June 23, 2010 20:28
-
-
Save olexpono/450499 to your computer and use it in GitHub Desktop.
Getting nice JSON out of node-xml / object parse --hack
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Assumes that it is in /node-xml2object/lib | |
// if otherwise, change the require | |
var sys = require('sys'), | |
xml2object = require('./xml2object'); | |
var xml = '<ListBucketResult><Name>bucket</Name><Prefix/><Marker/><MaxKeys>1000</MaxKeys><IsTruncated>false</IsTruncated><Contents><Key>my-image.jpg</Key><LastModified>2009-10-12T17:50:30.000Z</LastModified><ETag>"fba9dede5f27731c9771645a39863328"</ETag><Size>434234</Size><StorageClass>STANDARD</StorageClass><Owner><ID>8a6925ce4a7f21c32aa379004fef</ID><DisplayName>[email protected]</DisplayName></Owner></Contents><Contents><Key>my-third-image.jpg</Key><LastModified>2009-10-12T17:50:30.000Z</LastModified><ETag>"1b2cf535f27731c974343645a3985328"</ETag><Size>64994</Size><StorageClass>STANDARD</StorageClass><Owner><ID>8a69b1ddee97f21c32aa379004fef</ID><DisplayName>[email protected]</DisplayName></Owner></Contents></ListBucketResult>' | |
var indexes_to_array = function(o){ | |
var arr = []; | |
for( index in o ){ | |
arr = arr.concat(Array(o[index])); | |
} | |
return arr; | |
} | |
var obj_wo_functions = function(obj){ | |
var result = {}; | |
for (node in obj){ | |
if(typeof(obj[node]) == 'function'){ | |
// ignore functions like the plague | |
} | |
else if(obj[node].push){ | |
indexed_obj = obj_wo_functions(obj[node]); | |
result[node] = indexes_to_array(indexed_obj); | |
} | |
else if(typeof(obj[node]) == 'object'){ | |
result[node] = obj_wo_functions(obj[node]); | |
} | |
else { | |
result[node] = obj[node]; | |
} | |
} | |
return result; | |
} | |
var err_callback = function(smt, obj){ | |
parsed_nice_JSON = obj_wo_functions(obj.ListBucketResult) | |
sys.puts(sys.inspect(parsed_nice_JSON)); | |
} | |
var response = xml2object.parseString(xml, err_callback); | |
if(response){ | |
response.addCallback(function(obj) { | |
sys.puts(obj.ListBucketResult.Name); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment