Created
October 9, 2012 15:21
-
-
Save adeolaawoyemi/3859479 to your computer and use it in GitHub Desktop.
parse JSON object in AS3
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
private function parseJSON(o:*, spaces:int = 1):String { | |
var str:String = ""; | |
if(getTypeof(o) == "object") { | |
str += "{\n"; | |
for(var i:* in o) { | |
str += getSpaces(spaces) + i + "="; | |
if(getTypeof(o[i]) == "object" || getTypeof(o[i]) == "array") { | |
str += parseJSON(o[i], spaces + 1) + "\n"; | |
} else { | |
var type:String = getTypeof(o[i]); | |
if(type == "string") { | |
str += "\"" + o[i] + "\"\n"; | |
} else if(type == "number") { | |
str += o[i] + "\n"; | |
} | |
} | |
} | |
str += getSpaces(spaces - 1 < 0 ? 0 : spaces - 1) + "}"; | |
} else if(getTypeof(o) == "array") { | |
str += "[\n"; | |
var n:int = o.length; | |
for(i=0; i<n; i++) { | |
str += getSpaces(spaces) + "[" + i + "]="; | |
if(getTypeof(o[i]) == "object" || getTypeof(o[i]) == "array") { | |
str += parseJSON(o[i], spaces + 1) + "\n"; | |
} else { | |
type = getTypeof(o[i]); | |
if(type == "string") { | |
str += "\"" + o[i] + "\""; | |
} else if(type == "number") { | |
str += o[i]; | |
} | |
str += "\n"; | |
} | |
} | |
str += getSpaces(spaces - 1 < 0 ? 0 : spaces - 1) + "]"; | |
} | |
return str; | |
} | |
private function getSpaces(n:int):String { | |
var str:String = ""; | |
for(var i:int=0; i<n; i++) { | |
str += " "; | |
} | |
return str; | |
} | |
private function getTypeof(o:*):String { | |
return typeof(o) == "object" ? (o.length == null ? "object" : "array") : typeof(o); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment