Skip to content

Instantly share code, notes, and snippets.

@olexpono
Created June 23, 2010 20:28
Show Gist options
  • Save olexpono/450499 to your computer and use it in GitHub Desktop.
Save olexpono/450499 to your computer and use it in GitHub Desktop.
Getting nice JSON out of node-xml / object parse --hack
// 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>&quot;fba9dede5f27731c9771645a39863328&quot;</ETag><Size>434234</Size><StorageClass>STANDARD</StorageClass><Owner><ID>8a6925ce4a7f21c32aa379004fef</ID><DisplayName>mtd@amazon.com</DisplayName></Owner></Contents><Contents><Key>my-third-image.jpg</Key><LastModified>2009-10-12T17:50:30.000Z</LastModified><ETag>&quot;1b2cf535f27731c974343645a3985328&quot;</ETag><Size>64994</Size><StorageClass>STANDARD</StorageClass><Owner><ID>8a69b1ddee97f21c32aa379004fef</ID><DisplayName>mtd@amazon.com</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