Вложенный словарь и список JSON - PullRequest
0 голосов
/ 14 января 2019

это текущий вывод файла json:

{
    "filename.xml": 
    [
         {"TotalIssues": "352"}, 
         {"TotalVariants": "727"},
         {"TotalRemediations": "352"}, 
         {"TotalScanDuration": "1.03:31:39.2198925"}
    ],
    "http://www.web.com/":
    [
         {"TotalInformationalIssues": "352"}, 
         {"TotalInformationalIssues": "727"}
    ]
}

Я пытаюсь вывести 'http://www.web.com/' под вложенный файл filename.xml (который является корневым). это желаемый результат:

{"filename.xml":
 {"TotalIssues": "352",
"TotalVariants": "727",
"TotalRemediations": "352",
"TotalScanDuration": "1.03:31:39.2198925",
        "http://www.web.com/":
        [
           {"TotalInformationalIssues": "352"},
           {"TotalLowSeverityIssues": "727"}]

        }}

это исходный xml для разбора:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<XmlReport Name="x:\\projects\\www.web.com\\scan-2019-08-01-29762.scan" XmlExportVersion="2.0">
<ScanInfo>
  <Version>9.0.3.4</Version>
  <ServicePack />
</ScanInfo>
<Summary>
  <TotalIssues>352</TotalIssues>
  <TotalVariants>727</TotalVariants>
  <TotalRemediations>352</TotalRemediations>
  <TotalScanDuration>1.03:31:39.2198925</TotalScanDuration>
  <Hosts>
    <Host Name="http://www.web.com/">
      <TotalInformationalIssues>16</TotalInformationalIssues>
      <TotalLowSeverityIssues>1</TotalLowSeverityIssues>
      <TotalMediumSeverityIssues>0</TotalMediumSeverityIssues>
      <TotalHighSeverityIssues>0</TotalHighSeverityIssues>
      <Total>17</Total>
    </Host>
    <Host Name="https://www.web2.com/">
      <TotalInformationalIssues>332</TotalInformationalIssues>
      <TotalLowSeverityIssues>3</TotalLowSeverityIssues>
      <TotalMediumSeverityIssues>0</TotalMediumSeverityIssues>
      <TotalHighSeverityIssues>0</TotalHighSeverityIssues>
      <Total>335</Total>
    </Host>
  </Hosts>
</Summary>
</XmlReport>

это мой код:

import os
import logging
import sys
import json

logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', filename='/tmp/reports/myapp.log', level=logging.INFO)
data = {}


## stream read xml file

import xml.etree.ElementTree as ET
for filename in os.listdir("/tmp/reports"):
    try:
        if filename.endswith(".xml"):
            print("Handeling :"+os.path.join("/tmp/reports", filename))
            tree = ET.parse(os.path.join("/tmp/reports", filename))
            root = tree.getroot()

            data[filename] = []


            for item in root.findall('Summary'):
                TotalIssues = item.find('TotalIssues').text
                TotalVariants = item.find('TotalVariants').text
                TotalRemediations = item.find('TotalRemediations').text
                TotalScanDuration = item.find('TotalScanDuration').text

                data[filename].append({'TotalIssues':item.find('TotalIssues').text})
                data[filename].append({'TotalVariants':item.find('TotalVariants').text})
                data[filename].append({'TotalRemediations':item.find('TotalRemediations').text})
                data[filename].append({'TotalScanDuration':item.find('TotalScanDuration').text})


            data['http://www.web.com/'] = []

            for host in root.iter('Host'):

                TotalInformationalIssues = host.find('TotalInformationalIssues').text
                TotalLowSeverityIssues = host.find('TotalLowSeverityIssues').text



                data['http://www.web.com/'].append(host.attrib) ## http://www.web.com/
                data['http://www.web.com/'].append({'TotalInformationalIssues':host.find('TotalInformationalIssues').text})
                data['http://www.web.com/'].append({'TotalLowSeverityIssues':host.find('TotalLowSeverityIssues').text})


            print("Finished handeling "+filename)
            logging.info("Finished handeling "+filename)
            jsonfile = os.path.splitext(filename)[0]+'.json'
            print(jsonfile)
            with open('/tmp/reports/'+jsonfile, 'w') as outfile:
                json.dump(data, outfile)

        else:
            print("no file exist")
            logging.info("no file to process")
        #TotalIssues = item.find('TotalIssues').text
    except:
        print("Unexpected error:", sys.exc_info()[0])
        logging.error("Unexpected error:", sys.exc_info()[0])
        raise

Я не уверен, должен ли я использовать вложенные «для». если я тогда где? я не могу придумать способ объединить объект JSON и вложенный массив ценю твою помощь! Спасибо!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...