Python和JSON类

Python和JSON类,python,xml,json,Python,Xml,Json,我在使用JSON时遇到问题,我找不到合适的信息 首先,我成功地编写了用python而不是JSON创建XML的代码 我想知道如何转换下面的xml编写器类,以便转换为等效的JSON编写器类 from lxml import etree import re class XmlWriter: # Function create a xml def createNode(self,nodeName, parentNode = '', withAttribs = {}, withValue

我在使用JSON时遇到问题,我找不到合适的信息

首先,我成功地编写了用python而不是JSON创建XML的代码

我想知道如何转换下面的xml编写器类,以便转换为等效的JSON编写器类

from lxml import etree
import re

class XmlWriter:
    # Function create a xml
    def createNode(self,nodeName, parentNode = '', withAttribs = {}, withValue = ''):

        if nodeName != '':
            nodeName = re.sub(r'/', '_', nodeName)
            nodeName = re.sub(r'#','id',nodeName)
            if parentNode == '':
                # Create a parent node
                createdNode = etree.Element(nodeName)
            else:                  
                # Create a child node
                createdNode = etree.SubElement(parentNode, nodeName)

            # Put the Attributs with value    
            if  withAttribs !={}:
                for key,value in withAttribs.items():
                    createdNode.set(key,value)

            # Put the text content of the xml node
            if withValue != '':
                createdNode.text = withValue
            else:
                pass

            return createdNode

    # Print the XML for information
    def printXML(self,nodeName):
        print (etree.tostring(nodeName, pretty_print=True))

    # Save the XML on the file
    def saveXML(self,nodeName,filename):
        if nodeName != '' or filename !='':
            with open(filename, "w") as f:
                f.write(etree.tostring(nodeName, pretty_print=True))
        else:
            return False
我在几项研究中尝试创建树节点的等效物,例如:

{"menu": {
  "id": "file",
  "popup": {
    "menuitem": [
      {"value": "New", "onclick": "CreateNewDoc()"},
      {"value": "Open", "onclick": "OpenDoc()"},
      {"value": "Close", "onclick": "CloseDoc()"}
    ]
  }
}}
但如果您执行以下示例,如何创建类以获得结果:

n1 = CreateNode(name,parent_dependancy,value)...

非常感谢

JSON与XML非常不同,因此不可能获得等效的“JSON编写器”,因为您使用的是特定的XML特性属性。JSON允许您复制对象结构。就Python而言,JSON只允许您对dict、list和简单的标量值(如str、int等)进行编码

如果您有这样的结构,那么从中获取JSON文档非常简单:

>>> import json
>>> obj = {
'string-example' : 'foobar',
'int-example' : 42,
'float-example' : 3.14,
'list-example' : [ 0, 1, 1, 2, 3, 5, 8, 13, 21 ],
'tuple-example' : ( 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 ),
'dict-example' : { 'key' : 'value', 'key2' : 'value2' } }
>>> json.dumps(obj)
'{"list-example": [0, 1, 1, 2, 3, 5, 8, 13, 21], "int-example": 42, "string-example": "foobar", "tuple-example": [2, 3, 5, 7, 11, 13, 17, 19, 23, 29], "float-example": 3.14, "dict-example": {"key2": "value2", "key": "value"}}'

您可以使用JSON.loads以相同的方式读取JSON字符串。

您可以使用JSON转储进行打印。像这样:

print json.dumps( jsonData, indent=2 )
这很微妙,但是indent=2表示您希望数据打印得漂亮