Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python中解析JSON中的值_Python_Json - Fatal编程技术网

如何在Python中解析JSON中的值

如何在Python中解析JSON中的值,python,json,Python,Json,早上好,;我试图从URL生成的JSON文件中提取一些键值 我能够从URL中提取JSON而没有问题(打印第8行以供参考) JSON文件如下所示: 我在尝试解析JSON文件时收到以下错误- if ("absMinBreakingHeight" not in curr_conditions["swell"]): TypeError:列表索引必须是整数或片,而不是str“ 明白了。JSON是一个dict列表(见下文) 看 您将收到一个JSON数组,其中包含一系列表示特定时间段预测的数据,如下所示

早上好,;我试图从URL生成的JSON文件中提取一些键值

我能够从URL中提取JSON而没有问题(打印第8行以供参考)


JSON文件如下所示:



我在尝试解析JSON文件时收到以下错误-

if ("absMinBreakingHeight" not in curr_conditions["swell"]):
TypeError:列表索引必须是整数或片,而不是str“


明白了。JSON是一个dict列表(见下文)

您将收到一个JSON数组,其中包含一系列表示特定时间段预测的数据,如下所示:

所以你的代码应该在它上面做一个for循环

for forecast in forecasts:
    # your logic goes here
JSON


您必须将字符串转换为dict,并像这样更改主函数

import ast 

def main():
    curr_conditions = get_url()
    curr_conditions = ast.literal_eval(curr_conditions) # add this sentence
    if ("absMinBreakingHeight" not in curr_conditions["swell"]):
        print ("Error #001 JSON call failed, check your query is correct!]\n")
        exit()
    else:
        print('it worked')






感谢所有人的输入。我尝试了所有方法,所有方法都是正确的-JSON是dict的列表。将“[0]”应用到“curr_conditions[0][“swell”]”部分可以从JSON中提取值

def get_url():
    api_conditions_url = 'http://magicseaweed.com/api/' + API_KEY + '/forecast/?spot_id=' + PUTSBOROUGH_SPOT_ID
    print('Collecting data from - ' + api_conditions_url)
    try:
        f = urlopen(api_conditions_url)
    except:
        return []
    json_currently = f.read()
    print(f)
    f.close()
    return json.loads(json_currently)

def main():
    curr_conditions = get_url()
    if ("absMinBreakingHeight" not in curr_conditions[0]["swell"]):
        print ("Error #001 JSON call failed, check your query is correct!]\n")
        exit()
    else:
        print(curr_conditions[0]["swell"]["absMinBreakingHeight"])

if __name__ == "__main__":
    main()

看起来curr\u conditions是一个列表,您只向我们显示了其中的一部分。是否有可能
f=urlopen(api\u conditions\u url)
在您的
中尝试
除了
块失败,并且
get\u url
函数返回一个空列表外?@AlexHall-我如何将列表更改为我可以调用的内容。我使用相同的代码拉取不同的JSON文件,没有问题。我比较了两个JSON文件,看起来相同。请共享完整的JSONI文件ink您的json可能是DICT列表,即
[{},{}]
,您可能需要对其进行迭代并进行检查。例如
当前条件[0][“膨胀”]
[{
timestamp: 1366902000,
localTimestamp: 1366902000,
issueTimestamp: 1366848000,
fadedRating: 0,
solidRating: 0,
swell: {
    minBreakingHeight: 1,
    absMinBreakingHeight: 1.06,
    maxBreakingHeight: 2,
    absMaxBreakingHeight: 1.66,
    unit: "ft",
    components: {
         combined: {
         height: 1.1,
         period: 14,
         direction: 93.25,
         compassDirection: "W"
    },
    primary: {
         height: 1,
         period: 7,
         direction: 83.37,
         compassDirection: "W"
    },
    secondary: {
         height: 0.4,
         period: 9,
         direction: 92.32,
         compassDirection: "W"
    },
    tertiary: {
         height: 0.3,
         period: 13,
         direction: 94.47,
         compassDirection: "W"
     }
     }
},
wind: {
     speed: 10,
     direction: 85,
     compassDirection: "W",
     chill: 15,
     gusts: 13,
     unit: "mph"
},
condition: {
     pressure: 1020,
     temperature: 18,
     unitPressure: "mb",
     unit: "c"
},
charts: {
    swell: "http://cdn.magicseaweed.com/wave/750/1-1366902000-1.gif",
    period: "http://cdn.magicseaweed.com/wave/750/1-1366902000-2.gif",
    wind: "http://cdn.magicseaweed.com/gfs/750/1-1366902000-4.gif",
    pressure: "http://cdn.magicseaweed.com/gfs/750/1-1366902000-3.gif",
    sst: "http://cdn.magicseaweed.com/sst/750/1-1366902000-10.gif"
}
}]
import ast 

def main():
    curr_conditions = get_url()
    curr_conditions = ast.literal_eval(curr_conditions) # add this sentence
    if ("absMinBreakingHeight" not in curr_conditions["swell"]):
        print ("Error #001 JSON call failed, check your query is correct!]\n")
        exit()
    else:
        print('it worked')





def get_url():
    api_conditions_url = 'http://magicseaweed.com/api/' + API_KEY + '/forecast/?spot_id=' + PUTSBOROUGH_SPOT_ID
    print('Collecting data from - ' + api_conditions_url)
    try:
        f = urlopen(api_conditions_url)
    except:
        return []
    json_currently = f.read()
    print(f)
    f.close()
    return json.loads(json_currently)

def main():
    curr_conditions = get_url()
    if ("absMinBreakingHeight" not in curr_conditions[0]["swell"]):
        print ("Error #001 JSON call failed, check your query is correct!]\n")
        exit()
    else:
        print(curr_conditions[0]["swell"]["absMinBreakingHeight"])

if __name__ == "__main__":
    main()