1

I have imported a json file with python and still read the first json elements i need to add a loop for to read all the file

JSON file content

 [
        {
            "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
        },
.
.
.
.
.
    ]

and this is the python script

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

i know that i need to use

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

but i don't know where and how to use it, can you help ?

3
  • 1
    if severity=data[0]['severity'] < 4 is not valid Python. Commented May 2, 2018 at 15:14
  • in English, "boucle" is spelled "loop". Commented May 2, 2018 at 15:14
  • Please rephrase. Your question is unclear. What are you trying to do? What is a 'boucle'? Commented May 2, 2018 at 15:17

3 Answers 3

1

i know that i need to use for line in f: data.append(json.loads(line))"

Why on earth would you do that ??? You've already parsed the whole file, you have a list object back, all you have to do is iterate on the list.

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

for item in data:
    print(item)
Sign up to request clarification or add additional context in comments.

Comments

1

With the line

 data = json.load(json_data,)

you already have all the data loaded. Now you can just iterate over 'data':

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

Comments

0

Try:

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

1 Comment

Can you explain what this does? Just providing code is not often enough to provide full context to support your answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.