Skip to content Skip to sidebar Skip to footer

Looping Through Json Array In Python

I have JSON in an array that i am importing into my script 'ip_address': [ '192.168.0.1', '192.168.0.2', '192.168.0.3' ] I am loading the JSON and declaring a variable titled ip_a

Solution 1:

The reason why it's printing individual numbers is because the address is a string. Hence, it's not really each number that's being printed, but rather each letter of a string. Consider:

word = "abc"
for letter in word:
    print(letter)

# prints:
# a
# b
# c

Therefore, it means somewhere you're assigning individual IP addresses to a variable, and then iterate through that variable (which is a string). Without you providing more code on how you get the ip_address variable, it's hard to say where the problem is.

One way to print your IP addresses (assuming you have them in a dict):

addresses = {"ip_address": [
    "192.168.0.1",
    "192.168.0.2",
    "192.168.0.3"
]}

for address in addresses["ip_address"]:  # this gets you a list of IPs
      print(address)

Even if you have them somewhere else, the key insight to take away is to not iterate over strings, as you'll get characters (unless that's what you want).

Updated to address edits

Since I do not have the file (is it a file?) you are loading, I will assume I have exact string you posted. This is how you print each individual address with the data you have provided. Note that your situation might be slightly different, because, well, I do not know the full code.

# the string inside load() emulates your message
data = yaml.load('"ip_address": ["192.168.0.1", "192.168.0.2", "192.168.0.3"]')
ip_addresses = data.get('ip_address')

for address in ip_addresses: 
    print(address)

Solution 2:

In your case ip_address = '192.168.0.1'

Are you sure you have the right value in ip_address?


Solution 3:

I tried following :

ip_address = [ "192.168.0.1", "192.168.0.2", "192.168.0.3" ]

>>> ip_address = [ "192.168.0.1", "192.168.0.2", "192.168.0.3" ]

>>> 

>>> for i in ip_address:  

...     print i

... It printed

192.168.0.1

192.168.0.2

192.168.0.3

and it seems to be working fine for me .


Post a Comment for "Looping Through Json Array In Python"