2017-08-17 11 views
-1

にそれを書き込み、および、以下の記事で答えを与えられましたか?私は、私が書いているパス/ファイル名として "outputfile"を定義しなければならないことを理解していますが、入力ファイルがどこにあるのか分かりません。ネストされたJSONを解析し、CSV(再訪)はPythonに新しいビーイング

EDIT:わかりやすくするために、入力用のJSONファイルがあり、それを出力としてCSVファイルに変換したいと考えています。私は、上記の例を取り上げ、特定のJSONファイルを入力として指定するコードを書く方法を知りたいだけです。わかりやすくするために、JSONファイルの名前は同じですが、内容は毎日変わりますので、open() の場所とスクリプト内での呼び出し方法を知るだけで済みます。

EDIT_2:

inputfile = "/some/file.json" 
outputfile = "/some/file.csv" 
with open(inputfile, 'r') as inf: 
    with open(outputfile, 'w') as outf: 
     writer = None # will be set to a csv.DictWriter later 
      fp = open(inputfile, 'r') 
      json_value = fp.read() 
      data = json.loads(json_value) 

     for key, item in sorted(data.items(), key=itemgetter(0)): 
      row = {} 
      nested_name, nested_items = '', {} 
      for k, v in item.items(): 
       if not isinstance(v, dict): 
        row[k] = v 
       else: 
        assert not nested_items, 'Only one nested structure is supported' 
        nested_name, nested_items = k, v 

      if writer is None: 
       # build fields for each first key of each nested item first 
       fields = sorted(row) 

       # sorted keys of first item in key sorted order 
       nested_keys = sorted(sorted(nested_items.items(), key=itemgetter(0))[0][1]) 
       fields.extend('__'.join((nested_name, k)) for k in nested_keys) 

       writer = csv.DictWriter(outf, fields) 
       writer.writeheader() 

      for nkey, nitem in sorted(nested_items.items(), key=itemgetter(0)): 
       row.update(('__'.join((nested_name, k)), v) for k, v in nitem.items()) 
       writer.writerow(row) 

私は取得していますエラーがある...

for k, v in item.items(): 

はAttributeError: 'リスト' オブジェクトが持つ無属性のアイテムはありません "

私は私ではないかもしれないと思いますJSONファイルを正しく読んでいて... Pythonの初心者のストレス。

EDIT_3(更新JSON構造):ここでは は私が(NIST/NVD JSONファイル)を使用していますJSONファイルから1 'エントリ' です:

{ 
     "CVE_data_type" : "CVE", 
     "CVE_data_format" : "MITRE", 
     "CVE_data_version" : "4.0", 
     "CVE_data_numberOfCVEs" : "6208", 
     "CVE_data_timestamp" : "2017-08-14T18:06Z", 
     "CVE_Items" : [ { 
     "cve" : { 
      "CVE_data_meta" : { 
      "ID" : "CVE-2003-1547" 
      }, 
      "affects" : { 
      "vendor" : { 
       "vendor_data" : [ { 
       "vendor_name" : "francisco_burzi", 
       "product" : { 
        "product_data" : [ { 
        "product_name" : "php-nuke", 
        "version" : { 
         "version_data" : [ { 
         "version_value" : "6.5" 
         }, { 
         "version_value" : "6.5_beta1" 
         }, { 
         "version_value" : "6.5_rc3" 
         }, { 
         "version_value" : "6.5_rc2" 
         }, { 
         "version_value" : "6.5_rc1" 
         } ] 
        } 
        } ] 
       } 
       } ] 
      } 
      }, 
      "problemtype" : { 
      "problemtype_data" : [ { 
       "description" : [ { 
       "lang" : "en", 
       "value" : "CWE-79" 
       } ] 
      } ] 
      }, 
      "references" : { 
      "reference_data" : [ { 
       "url" : "http://secunia.com/advisories/8478" 
      }, { 
       "url" : "http://securityreason.com/securityalert/3718" 
      }, { 
       "url" : "http://www.securityfocus.com/archive/1/archive/1/316925/30/25250/threaded" 
      }, { 
       "url" : "http://www.securityfocus.com/archive/1/archive/1/317230/30/25220/threaded" 
      }, { 
       "url" : "http://www.securityfocus.com/bid/7248" 
      }, { 
       "url" : "https://exchange.xforce.ibmcloud.com/vulnerabilities/11675" 
      } ] 
      }, 
      "description" : { 
      "description_data" : [ { 
       "lang" : "en", 
       "value" : "Cross-site scripting (XSS) vulnerability in block-Forums.php in the Splatt Forum module for PHP-Nuke 6.x allows remote attackers to inject arbitrary web script or HTML via the subject parameter." 
      } ] 
      } 
     }, 
     "configurations" : { 
      "CVE_data_version" : "4.0", 
      "nodes" : [ { 
      "operator" : "OR", 
      "cpe" : [ { 
       "vulnerable" : true, 
       "cpeMatchString" : "cpe:/a:francisco_burzi:php-nuke:6.5", 
       "cpe23Uri" : "cpe:2.3:a:francisco_burzi:php-nuke:6.5:*:*:*:*:*:*:*" 
      }, { 
       "vulnerable" : true, 
       "cpeMatchString" : "cpe:/a:francisco_burzi:php-nuke:6.5_beta1", 
       "cpe23Uri" : "cpe:2.3:a:francisco_burzi:php-nuke:6.5_beta1:*:*:*:*:*:*:*" 
      }, { 
       "vulnerable" : true, 
       "cpeMatchString" : "cpe:/a:francisco_burzi:php-nuke:6.5_rc1", 
       "cpe23Uri" : "cpe:2.3:a:francisco_burzi:php-nuke:6.5_rc1:*:*:*:*:*:*:*" 
      }, { 
       "vulnerable" : true, 
       "cpeMatchString" : "cpe:/a:francisco_burzi:php-nuke:6.5_rc2", 
       "cpe23Uri" : "cpe:2.3:a:francisco_burzi:php-nuke:6.5_rc2:*:*:*:*:*:*:*" 
      }, { 
       "vulnerable" : true, 
       "cpeMatchString" : "cpe:/a:francisco_burzi:php-nuke:6.5_rc3", 
       "cpe23Uri" : "cpe:2.3:a:francisco_burzi:php-nuke:6.5_rc3:*:*:*:*:*:*:*" 
      } ] 
      } ] 
     }, 
     "impact" : { 
      "baseMetricV2" : { 
      "cvssV2" : { 
       "vectorString" : "(AV:N/AC:M/Au:N/C:N/I:P/A:N)", 
       "accessVector" : "NETWORK", 
       "accessComplexity" : "MEDIUM", 
       "authentication" : "NONE", 
       "confidentialityImpact" : "NONE", 
       "integrityImpact" : "PARTIAL", 
       "availabilityImpact" : "NONE", 
       "baseScore" : 4.3 
      }, 
      "severity" : "MEDIUM", 
      "exploitabilityScore" : 8.6, 
      "impactScore" : 2.9, 
      "obtainAllPrivilege" : false, 
      "obtainUserPrivilege" : false, 
      "obtainOtherPrivilege" : false, 
      "userInteractionRequired" : true 
      } 
     }, 
     "publishedDate" : "2003-12-31T05:00Z", 
     "lastModifiedDate" : "2017-08-08T01:29Z" 
     }] 
} 

私は(キーがヘッダになりたいですlastModifiedDate、cpe23Uriなど)をCSVファイル用に作成します。空白を除外して、CSVファイルにヘッダとデータがあれば、そのカラムだけを選択することができます。

+0

@MartjinPieters ...あなたがリンクされ、質問に答え...あなたも、このいずれかを答えることができますか? :p –

+0

この質問は、あなたが既にリストにデータを持っていることを前提としています。それは入力ファイルから来る必要はなく、実行する計算から来ることができます。 – Barmar

+0

別のファイルから取得したい場合は、そのファイルを開いて適切な方法で解析するコードを書いてください。 – Barmar

答えて

0

幸いにも、あなたのJSONデータは、json.load()が読んで解析するのに有効です。しかし、キーをヘッダーにしたいと言っているだけでは、具体的ではありません。それぞれのエントリのレベルがそれぞれ異なります'(あなたが下に示すように)。リンクされた質問のOPが入力だけでなく、CSVファイル内の値の列にマッピングされているかどうかを定義する方法にも注意してください。マッピングキーについて手を振るだけでなくファイルヘッダーに追加します。

それにかかわらず、これを行うのに役立つものがあります。これは、読んでいるJSONオブジェクトの最上位の"CVE_Items"キーに関連付けられているリストの各エントリを読み込み、適切に書式設定して出力します。アウトプットからは、CSVファイルへの行として抽出して書き込む列を選択し、その行にコードを記入する必要があります。あなたがあなたの質問に追加されたサンプルJSONデータ内の単一のエントリのための

import json 

inputfile = "some_file.json" 
outputfile = "some_file.csv" 

with open(outputfile, 'w', newline='') as outf: 
    with open(inputfile, 'r') as fp: 
     data = json.load(fp) 

    # Here is where you should convert each entry into a row of CSV data. 
    # All this does now is show the contents of each entry in "CVE_Items" list. 
    for entry in data["CVE_Items"]: 
     print(json.dumps(entry, indent=4)) 

出力:

{ 
    "cve": { 
     "CVE_data_meta": { 
      "ID": "CVE-2003-1547" 
     }, 
     "affects": { 
      "vendor": { 
       "vendor_data": [ 
        { 
         "vendor_name": "francisco_burzi", 
         "product": { 
          "product_data": [ 
           { 
            "product_name": "php-nuke", 
            "version": { 
             "version_data": [ 
              { 
               "version_value": "6.5" 
              }, 
              { 
               "version_value": "6.5_beta1" 
              }, 
              { 
               "version_value": "6.5_rc3" 
              }, 
              { 
               "version_value": "6.5_rc2" 
              }, 
              { 
               "version_value": "6.5_rc1" 
              } 
             ] 
            } 
           } 
          ] 
         } 
        } 
       ] 
      } 
     }, 
     "problemtype": { 
      "problemtype_data": [ 
       { 
        "description": [ 
         { 
          "lang": "en", 
          "value": "CWE-79" 
         } 
        ] 
       } 
      ] 
     }, 
     "references": { 
      "reference_data": [ 
       { 
        "url": "http://secunia.com/advisories/8478" 
       }, 
       { 
        "url": "http://securityreason.com/securityalert/3718" 
       }, 
       { 
        "url": "http://www.securityfocus.com/archive/1/archive/1/316925/30/25250/threaded" 
       }, 
       { 
        "url": "http://www.securityfocus.com/archive/1/archive/1/317230/30/25220/threaded" 
       }, 
       { 
        "url": "http://www.securityfocus.com/bid/7248" 
       }, 
       { 
        "url": "https://exchange.xforce.ibmcloud.com/vulnerabilities/11675" 
       } 
      ] 
     }, 
     "description": { 
      "description_data": [ 
       { 
        "lang": "en", 
        "value": "Cross-site scripting (XSS) vulnerability in block-Forums.php in the Splatt Forum module for PHP-Nuke 6.x allows remote attackers to inject arbitrary web script or HTML via the subject parameter." 
       } 
      ] 
     } 
    }, 
    "configurations": { 
     "CVE_data_version": "4.0", 
     "nodes": [ 
      { 
       "operator": "OR", 
       "cpe": [ 
        { 
         "vulnerable": true, 
         "cpeMatchString": "cpe:/a:francisco_burzi:php-nuke:6.5", 
         "cpe23Uri": "cpe:2.3:a:francisco_burzi:php-nuke:6.5:*:*:*:*:*:*:*" 
        }, 
        { 
         "vulnerable": true, 
         "cpeMatchString": "cpe:/a:francisco_burzi:php-nuke:6.5_beta1", 
         "cpe23Uri": "cpe:2.3:a:francisco_burzi:php-nuke:6.5_beta1:*:*:*:*:*:*:*" 
        }, 
        { 
         "vulnerable": true, 
         "cpeMatchString": "cpe:/a:francisco_burzi:php-nuke:6.5_rc1", 
         "cpe23Uri": "cpe:2.3:a:francisco_burzi:php-nuke:6.5_rc1:*:*:*:*:*:*:*" 
        }, 
        { 
         "vulnerable": true, 
         "cpeMatchString": "cpe:/a:francisco_burzi:php-nuke:6.5_rc2", 
         "cpe23Uri": "cpe:2.3:a:francisco_burzi:php-nuke:6.5_rc2:*:*:*:*:*:*:*" 
        }, 
        { 
         "vulnerable": true, 
         "cpeMatchString": "cpe:/a:francisco_burzi:php-nuke:6.5_rc3", 
         "cpe23Uri": "cpe:2.3:a:francisco_burzi:php-nuke:6.5_rc3:*:*:*:*:*:*:*" 
        } 
       ] 
      } 
     ] 
    }, 
    "impact": { 
     "baseMetricV2": { 
      "cvssV2": { 
       "vectorString": "(AV:N/AC:M/Au:N/C:N/I:P/A:N)", 
       "accessVector": "NETWORK", 
       "accessComplexity": "MEDIUM", 
       "authentication": "NONE", 
       "confidentialityImpact": "NONE", 
       "integrityImpact": "PARTIAL", 
       "availabilityImpact": "NONE", 
       "baseScore": 4.3 
      }, 
      "severity": "MEDIUM", 
      "exploitabilityScore": 8.6, 
      "impactScore": 2.9, 
      "obtainAllPrivilege": false, 
      "obtainUserPrivilege": false, 
      "obtainOtherPrivilege": false, 
      "userInteractionRequired": true 
     } 
    }, 
    "publishedDate": "2003-12-31T05:00Z", 
    "lastModifiedDate": "2017-08-08T01:29Z" 
} 
+0

そのコードをありがとう。上記のように印刷することができます。これをどのようにしてCSVファイルに書き込むことができますか? –

+0

私はそれをどのように平坦化するのか分かりません。私が言ったように、リンクされた質問では、OPはJSONデータのさまざまな部分をどのようにCSV行に変換するかを指定しました。 JSONは主にツリーデータ構造ですが、CSVはテーブル(または2D配列/マトリックス)であり、一方から他方へのマッピングは任意です。私はあなたのためにその方法を決めることはできませんが、あなたが望むものを少なくとも定義することができれば、おそらくそれを実装する方法を示すことができます。非常に重要な点の1つは、 '' version_data ''のような、複数の値が関連付けられたものがどのようにして単一の行に変換されるかです。 – martineau

+0

JSONファイル内のデータは、key:valueのペアになっているようですが、上記の「version_data:」のように、指定されたキーに複数の値があることがあります。ペアの「キー」部分を列のヘッダーにし、「値」を列としてデータとして埋めたいと思っています。あるキーの複数の値の場合、指定されたキーのすべての値を連結する必要があります。 –

関連する問題