簡體   English   中英

用python導入JSON文件

[英]Importing JSON file with python

我已經用python導入了一個json文件,但仍然讀取了我需要添加一個循環以讀取所有文件的第一個json元素

JSON文件內容

 [
        {
            "severity": 4,
            "status": "OPEN",
            "id": 1987,
            "description": "Multiple Login Failures for the Same User containing Bad Username",
            "start_time": 1525269490400
        },
        {
            "severity": 4,
            "status": "OPEN",
            "id": 1986,
            "description": "Multiple Login Failures for the Same User containing Bad Username",
            "start_time": 1525269181679
        },
.
.
.
.
.
    ]

這是python腳本

# Prepare the sample Alert

with open('output.json') as json_data:
    data = json.load(json_data,) 
if severity=data[0]['severity'] < 4:
    severity=1
elif severity=data[0]['severity'] > 6:
    severity=3
else:
    severity=2  
alert = Alert(title=data[0]['description'],
              date=data[0]['start_time'],
              severity=severity,
              description='N/A',
              type='Offense',
              source='QradarSiem',
              sourceRef=data[0]['id'])

我知道我需要使用

for line in f:
    data.append(json.loads(line))

但我不知道在哪里以及如何使用它,您能幫忙嗎?

我知道我需要for line in f: data.append(json.loads(line))"使用for line in f: data.append(json.loads(line))"

你到底為什么要這樣做? 您已經解析了整個文件,有了列表對象,您要做的就是在列表上進行迭代。

with open('output.json') as json_data:
    data = json.load(json_data,) 

for item in data:
    print(item)

用線

 data = json.load(json_data,)

您已經加載了所有數據。 現在您可以遍歷“數據”:

for item in data:
    if item['severity'] == 4:
        do_something(item)

嘗試:

import json
with open("infile.json","r") as infile:
    val = infile.read()
    json=json.loads(val)
print(json)

暫無
暫無

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

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