Master Irfan
Master Irfan

Reputation: 7

Extracting values in JSON text file in Python

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

Upvotes: 0

Views: 732

Answers (3)

Jab
Jab

Reputation: 27485

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

Upvotes: 1

chepner
chepner

Reputation: 531155

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'])}")

Upvotes: 0

Sam
Sam

Reputation: 46

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

Upvotes: 1

Related Questions