Created
January 3, 2016 13:48
-
-
Save brian-lim-42/d56799f46c3084e06093 to your computer and use it in GitHub Desktop.
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
function objToJson (obj, rootName) { | |
var root = {}; | |
root[rootName] = {}; | |
objToJsonRecursive(root[rootName], obj); | |
return root; | |
} | |
function objToJsonRecursive(root, obj) { | |
for (var key in obj) { | |
if (obj.hasOwnProperty(key)) { | |
if (Object.prototype.toString.call(obj[key]) === '[object Array]') { | |
root[key] = []; | |
for (var innerKey in obj[key]) { | |
var innerRoot = {}; | |
innerRoot['$class'] = obj[key][innerKey].constructor.name; | |
console.log(innerKey); | |
objToJsonRecursive(innerRoot, obj[key][innerKey]); | |
root[key].push(innerRoot); | |
} | |
} | |
else if (typeof obj[key] === 'object') { | |
var innerRoot = {}; | |
innerRoot['$class'] = obj[key].constructor.name; | |
root[key] = []; | |
root[key].push(innerRoot); | |
objToJsonRecursive(innerRoot, obj[key]); | |
} | |
else { | |
root[key] = obj[key]; | |
} | |
} | |
} | |
if (!obj.hasOwnProperty('$class') && typeof obj.constructor !== 'undefined') { | |
root['$class'] = obj.constructor.name; | |
} | |
} | |
/* | |
test case | |
*/ | |
/* | |
test case | |
*/ | |
function ClassA() | |
{ | |
this.name = "Brian"; | |
this.job = "Developer"; | |
} | |
function ClassB() | |
{ | |
this.chicken = "thigh"; | |
this.made = "made in canada"; | |
} | |
var testObj = new ClassA(); | |
var testObj2 = new ClassA(); | |
testObj2.name = "David"; | |
var testObj3 = new ClassB(); | |
var testObj4 = new ClassB(); | |
testObj.david = testObj2; | |
testObj.chickenList = []; | |
testObj.chickenList[0] = testObj3; | |
testObj.chickenList[1] = testObj4; | |
var result = objToJson(testObj, 'testxml'); | |
console.log(JSON.stringify(testObj)); | |
console.log(JSON.stringify(result)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment