无法正确读取json文件

2024-09-27 09:31:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从联机https://api.myjson.com/bins/y2k4y读取json文件,并基于参数“ipv4”、“ipv6”进行打印。我已经用python编写了代码。它向我展示了这个错误。请建议我解决这个问题

Python代码

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")

错误

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

json文件https://api.myjson.com/bins/y2k4y


Tags: tohttpscomapijsondataresponseglobal

热门问题