【问题标题】:Convert XML to JSON with python, attributes of the father after the child nodes in the JSON用python将XML转换为JSON,JSON中子节点后面的父属性
【发布时间】:2021-01-07 15:50:15
【问题描述】:

我需要使用python将一个文件XML转换为JSON,但我需要将父亲的属性放在JSON中的子节点之后

我现在的代码是这样的。

def generate_json(self, event=None):
    # opening the xml file
    with open(self.fn ,"r") as xmlfileObj:
        data_dict =  lib.xmltodict.parse(xmlfileObj.read(),attr_prefix='_')

        xmlfileObj.close()           

    jsonObj= json.dumps(data_dict, sort_keys=False)
    restored = json.loads(jsonObj)
    #storing json data to json file
    with open("data.json", "w") as jsonfileObj:
        jsonfileObj.write(jsonObj)
        jsonfileObj.close()

我需要这个;

{
  "datasetVersion": {
    "metadataBlocks": {
      "citation": {
        "fields": [
          {
            "value": "Darwin's Finches",
            "typeClass": "primitive",
            "multiple": false,
            "typeName": "title"
          }
        ],
        "displayName": "Citation Metadata"
      }
    }
  }
}

代替:

{
  "datasetVersion": {
    "metadataBlocks": {
      "citation": {
        "displayName": "Citation Metadata",
        "fields": [
          {
            "value": "Darwin's Finches",
            "typeClass": "primitive",
            "multiple": false,
            "typeName": "title"
          }
        ]       
      }
    }
  }
}

不按字母顺序改变sort_keys=False,我只需要将节点father的属性改为final即可。

在某些网站上制作我需要的内容: https://www.convertjson.com/xml-to-json.htm

还有一个不怎么样:

http://www.utilities-online.info/xmltojson/#.X_crINhKiUk

有人可以帮我吗?

【问题讨论】:

  • 顺序真的重要吗?它不应该适用于大多数应用程序。
  • 是的,因为从这个方案中可以使用先前开发的较低级别的子系统:/
  • AFAIK json 对象按标准是无序的,因此除非您使用自定义 json 解析器或在子系统上进行一些验证,否则无论如何都无关紧要。

标签: python json xml xmltodict


【解决方案1】:

我可以使用https://pypi.org/project/xmljson/ 库进行格式化,我修改了BadgerFish 样式

class BadgerFish(XMLData): # 约定从项目中更改了前缀_并排序父节点的属性 '''使用 BadgerFish 约定在 XML 和数据之间转换''' def init(self, **kwargs): super(BadgerFish, self).init(attr_prefix='_', text_content='$', **kwargs)

我把属性的前缀改成了“_”

否则只改了**#修改把父属性改完,代码中怎么看

def data(self, root):
        '''Convert etree.Element into a dictionary'''
        value = self.dict()
        children = [node for node in root if isinstance(node.tag, basestring)]
  
        if root.text and self.text_content is not None:
            text = root.text
            if text.strip():
                if self.simple_text and len(children) == len(root.attrib) == 0:
                    value = self._fromstring(text)
                else:
                    value[self.text_content] = self._fromstring(text)
        count = Counter(child.tag for child in children)
        for child in children:
            # if child.tag == "System_State_Entry": print(child.tag)
            if count[child.tag] == 1:
                value.update(self.data(child))
            else:
                result = value.setdefault(child.tag, self.list())
                result += self.data(child).values()
        # if simple_text, elements with no children nor attrs become '', not {}
        if isinstance(value, dict) and not value and self.simple_text:
            value = ''

        **# modify to put the father atributes to finish
        for attr, attrval in root.attrib.items():
            attr = attr if self.attr_prefix is None else self.attr_prefix + attr
            value[attr] = self._fromstring(attrval)**     
        return self.dict([(root.tag, value)])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-04
    • 2021-10-26
    • 2016-08-09
    • 1970-01-01
    • 1970-01-01
    • 2016-12-19
    • 1970-01-01
    相关资源
    最近更新 更多