AS3: converting XML to JSON object
posted in /home/ActionScript on 2011-04-02 |
I'm absolutely sure that you are using external data in your flash/flex applications. It is a good practice to transfer information in XML format. Most of the projects that I'm working on also use XML and in most of them I have a class that converts the data to JSON object. The problem with this workflow is that the parser's logic is always different because the XML is different. These days I wrote a class that solved this problem and directly converted every given XML file to a JSON object.
The XML file that I tested with:
The result:
The usage:
There are two things that you have to pay attention to:
1. When you have a node which doesn't have children (i.e. a text node), but it has attributes. For example:
is converted to:
I.e. the text in the node is attached to _content property.
2. When you have a node which should be an array of objects, but currently it has only one child. In this case the script will not recognize your child as an element of an array, but will add it as a property. That's why you should describe those nodes in arrays property of XML2JSON class. For example:
will be converted to:
Mark img node as an array:
And the result will be:
And here is the code of the class:
P.S.
if you are wondering how to print out JSON in AS3 check out this article.
The XML file that I tested with:
The result:
The usage:
There are two things that you have to pay attention to:
1. When you have a node which doesn't have children (i.e. a text node), but it has attributes. For example:
is converted to:
I.e. the text in the node is attached to _content property.
2. When you have a node which should be an array of objects, but currently it has only one child. In this case the script will not recognize your child as an element of an array, but will add it as a property. That's why you should describe those nodes in arrays property of XML2JSON class. For example:
will be converted to:
Mark img node as an array:
And the result will be:
And here is the code of the class:
P.S.
if you are wondering how to print out JSON in AS3 check out this article.
Delicious