user1850484
user1850484

Reputation: 388

Cannot read json file properly

I want to read json file from online https://api.myjson.com/bins/y2k4y and print based on the parameter like 'ipv4', 'ipv6'. I have written code in python. It is showing me this error. Please advise me to solve this problem.

Python code

import requests
import json

# Method To Get REST Data In JSON Format
def getResponse(url,choice):

    response = requests.get(url)

    if(response.ok):
        jData = json.loads(response.content)
        if(choice=="deviceInfo"):
            print("working")
            deviceInformation(jData)
    else:
        print("NOT working")
        response.raise_for_status()


# Parses JSON Data To Find Switch Connected To H4
def deviceInformation(data):
    global switch
    global deviceMAC
    global hostPorts
    switchDPID = ""
    print ( data)
    for i in data:
        print ("i: ", i['ipv4'])


deviceInfo = "https://api.myjson.com/bins/y2k4y"
getResponse(deviceInfo,"deviceInfo")

Error

  File "E:/aaa/e.py", line 27, in deviceInformation
    print ("i: ", i['ipv4'])
TypeError: string indices must be integers

json file https://api.myjson.com/bins/y2k4y

Upvotes: 1

Views: 136

Answers (2)

N N K Teja
N N K Teja

Reputation: 435

Try using for i in data['devices']: instead of for i in data:

Upvotes: 1

Gagan T K
Gagan T K

Reputation: 728

jData is a dict with only 1 key devices. devices contain all the other info which you require.

Change for i in data to for i in data['devices']:

for i in data['devices']:
        print ("i: ", i['ipv4'])
        print ("i: ", i['ipv6'])

Upvotes: 1

Related Questions