SitePoint Sponsor |
|
User Tag List
Results 1 to 3 of 3
Thread: Convert JSON to XML
-
Oct 24, 2007, 09:20 #1
- Join Date
- Feb 2003
- Location
- Knoxville, TN
- Posts
- 531
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Convert JSON to XML
i have a javascript object that i'm wanting to convert into an XML document.
basically, i'm wanting to make this as dynamic as possible because i'm not always going to have the same attributes for each conversion, and i'm not sure how to loop through an objects attributes, pull the attribute name, etc... pulling the value is easy once i know the names of the available attributes.
for example, data.People[0].Person[2] might have .FirstName, .LastName, .MaidenName, etc... while the others do not.
Code:<People> <Person FirstName="Bob" LastName="Smith" /> <Person FirstName="Mary" LastName="Jones" MaidenName="Brown" /> <Person FirstName="Richard" LastName="Williams" /> </People>
-
Oct 24, 2007, 12:59 #2
- Join Date
- Feb 2003
- Location
- Knoxville, TN
- Posts
- 531
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
this is a start... it at least returns "People".
Code:for (var key in object) { alert(key); }
-
Oct 24, 2007, 14:44 #3
- Join Date
- Jun 2004
- Location
- Copenhagen, Denmark
- Posts
- 6,157
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Code:/** * <p>Serialize any object to an XML string. All properties are serialized using the property name * as the XML element name. Array elements are rendered as <code>array-item</code> elements, * using their index/key as the value of the <code>key</code> attribute.</p> * @argument anyObject the object to serialize * @argument objectName a name for that object * @return the XML serializationj of the given object as a string */ Sarissa.xmlize = function(anyObject, objectName, indentSpace){ indentSpace = indentSpace?indentSpace:''; var s = indentSpace + '<' + objectName + '>'; var isLeaf = false; if(!(anyObject instanceof Object) || anyObject instanceof Number || anyObject instanceof String || anyObject instanceof Boolean || anyObject instanceof Date){ s += Sarissa.escape(""+anyObject); isLeaf = true; }else{ s += "\n"; var itemKey = ''; var isArrayItem = anyObject instanceof Array; for(var name in anyObject){ s += Sarissa.xmlize(anyObject[name], (isArrayItem?"array-item key=\""+name+"\"":name), indentSpace + " "); }; s += indentSpace; }; return s += (objectName.indexOf(' ')!=-1?"</array-item>\n":"</" + objectName + ">\n"); }; /** * Escape the given string chacters that correspond to the five predefined XML entities * @param sXml the string to escape */ Sarissa.escape = function(sXml){ return sXml.replace(/&/g, "&") .replace(/</g, "<") .replace(/>/g, ">") .replace(/"/g, """) .replace(/'/g, "'"); };
Bookmarks