繁体   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