0

I currently have a text file in JSON format of ip addresses with their ports, example:

[
 {
   "ip": "192.0.3.202",
   "port": [
    22,
    53,
    80,
    443]
  },
{
   "ip": "192.0.3.253",
   "port": [
    179]
  }
]

I want to print out only the ip and on another line with ports. Expected output:

IP: 192.0.3.202
Port: 22,53,80,443

IP: 192.0.3.253
Port: 179

I have tried doing this:

i=0
while True:
    ip_test = open('test.txt', 'r')
    ip_line=ip_test.readlines()
    a=ip_line[i].strip("{\"ip\": ")
    print(a)

However my output is only stripping out the first few characters

1

3 Answers 3

1

Just manipulating the text perhaps isn't the best way to go about this, as Python offers support for JSON in the standard libraries.

You can access the library by using import json and then manipulating the resulting array.

See the documentation here: https://docs.python.org/3/library/json.html

Sign up to request clarification or add additional context in comments.

Comments

1

Use the json module :

import json

with open('test.txt', 'r') as f:
    for address in json.load(f):
        print(f"ID: {address['ip']}\nPort: {', '.join(map(str, address['port']))}\n")

Output:

ID: 192.0.3.202
Port: 22, 53, 80, 443

ID: 192.0.3.253
Port: 179

Comments

0

strip doesn't remove a prefix; it removes any leading or trailing character that appears in the iterable argument.

But you shouldn't be trying to parse the contents manually; use json to parse the data and work with the resulting dict.

import json

with open('test.txt') as ip_test:
    data = json.load(ip_test)

for obj in data:
    print(f"IP: {obj['ip']}")
    print(f"Port: {','.join(obj['port'])}")

Comments

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.