簡體   English   中英

將 XML 轉換為 JSON 與 python,Z0ECD11C1D7A287401D8D148A 中子節點之后的父屬性

[英]Convert XML to JSON with python, attributes of the father after the child nodes in the JSON

我需要使用 python 將一個文件 XML 轉換為 JSON,但我需要將父親的屬性放在 Z7702F11C1D7A2B8 中的子節點之后

我現在的代碼是這樣的。

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 ,我只需要將節點父親的屬性更改為最終。

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

還有一個不怎么樣:

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

有人可以幫助我嗎?

我可以使用https://pypi.org/project/xmljson/庫格式化,我修改了 BadgerFish 樣式

class BadgerFish(XMLData): # 約定從項目中更改為前綴 _ 並排序父節點的屬性 '''在 XML 和使用 BadgerFish 約定的數據之間轉換''' def init (self, **kwargs): super (獾魚,自我)。 初始化(attr_prefix='_', text_content='$', **kwargs)

我將屬性的前綴更改為“_”

by 否則只改了**# modify 把父屬性改完,怎么看代碼

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)])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM