tree representation of Python data

Thomas Passin list1 at tompassin.net
Wed Feb 8 09:37:19 EST 2023


On 2/8/2023 6:39 AM, Shaozhong SHI wrote:
> What is the robust way to use Python to read in an XML and turn it into 
> a JSON file?
> 
> JSON dictionary is actually a tree.  It is much easier to manage the 
> tree-structured data.

XML and JSON are both for interchanging data.  What are you trying to 
accomplish? XML elements form a tree, XML attributes can be thought of 
as a dictionary.   JSON can contain both lists and associative arrays 
(dictionaries).  Personally, I would not say it's easier to "manage" 
tree-structured data than dictionaries, but either way it sounds like 
you want to send or receive data, rather than "managing" data in program 
data structures.

So why do you want to convert data in XML form to JSON?  Once you have 
XML ingested into some Python data structure, you can use the json 
library to output JSON- see

https://docs.python.org/3/library/json.html

There is a pip-installable program (which I have never used), xmltodict, 
that stores an XML file as a Python dictionary.  You then can write it 
to JSON as above.  I don't know how general this program is - XML is not 
isomorphic to JSON, but maybe your XML sources never use anything 
besides elements and attributes, and don't use namespaces.  Then it's 
pretty easy.



More information about the Python-list mailing list