Looping through json array in python

11,345

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 .

Share:
11,345
Petter Friberg
Author by

Petter Friberg

Born in Sweden but living in Italy, I have developed software both in C# and Java for several years and stack overflow has always provided good answers so it was time that I started to contribute.. I have seen that in java section there are a lot of FGITW so I'm under the oak tree in jasper-reports. Not much repzz but I got a very nice award from the JasperSoft Community, Q3 2016 Featured Community Member, thanks again! I'm one of the developers of this heat detection, duplicate questions and cherry picking Queen present in the SOBotics room, ping me in there if you need to tell me something interesting. You may also find me fighting spam from the SOCVR chat In jasper-reports be careful you need font-extension to display correctly font's in pdf (there is a lot of confusion), Font is not available to the JVM with Jasper Reports and many answers have been deprecated over time. I have also tried to create some Q-A post How can I export report to PDF/A-1a, PDF/A-1b? How can I test if my font is rendered correctly in pdf? but with mixed feelings, so now I limit myself to answer the questions as they arrive.

Updated on December 02, 2022

Comments

  • Petter Friberg
    Petter Friberg over 1 year

    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_address.

    data = yaml.load(message)
        for d in data: 
            ip_address = (d.get('ip_address'))
    

    I am attempting to loop using python through the ip addresses.

    for address in data['ip_address']:  
          print(address)
    

    I am now getting an error that tells me

    string indices must be integers, not str
    
    • e4c5
      e4c5 about 7 years
      show how ip_address variable is created
    • gonczor
      gonczor about 7 years
      Paste full code. This part is useless.
    • CalvT
      CalvT about 7 years
      Please do not vandalize your posts. Once you've posted a question, you have licensed the content to the Stack Overflow community at large (under the CC-by-SA license). If you would like to disassociate this post from your account, see What is the proper route for a disassociation request?
  • Admin
    Admin about 7 years
    Yes, this error only occurs when i put the for loop in. This is a loop problem, cant figure out why its looping through individual characters and not strings.
  • Szabolcs Dombi
    Szabolcs Dombi about 7 years
    because you set ip_address to a string not to a list. you can print the type of the variable: print(type(ip_address))
  • Szabolcs Dombi
    Szabolcs Dombi about 7 years
    for ip in obj['ip_address'] will work fine where obj is the loaded json
  • trotta
    trotta about 7 years
    because you're iterating through a list and that wasn't the question
  • Admin
    Admin about 7 years
    Ran that, but I'm getting an error :list indices must be integers, not str
  • cegas
    cegas about 7 years
    That was only an example - it will most likely not work in the code you have (as I do not know how it looks). You should edit your question to include more information. For starters, where ip_address in for loop is defined.
  • cegas
    cegas about 7 years
    I have updated the answer. I'm still a little unclear what the message in yaml.load(message) looks like exactly, so it's a bit hard to guarantee this will work. However, the idea of what must be done should be clear. If it doesn't, please update the question specifying what message looks like (a small, working snippet is enough) and I will try to help.