无法遍历webservice Python的JSON输出

时间:2013-12-01 21:43:35

标签: json api list python-2.7 dictionary

我有一个Web服务调用(HTTP Get),我的Python脚本在其中返回一个JSON响应。响应看起来是字典列表。该脚本的目的是遍历每个字典,提取每个元数据(即“ClosePrice”:“57.74”),并将每个字典写入Mssql中自己的行。

问题是,我不认为Python将API调用中的JSON输出识别为字典列表,当我尝试for循环时,我收到错误must be int not str。我已经尝试将输出转换为列表,字典,元组。我也尝试使用List Comprehension,没有运气。此外,如果我从API调用中复制/粘贴数据并将其分配给变量,它会识别出其没有问题的字典列表。任何帮助,将不胜感激。我正在使用Python 2.7。

以下是正在进行的http调用:http://test.kingegi.com/Api/QuerySystem/GetvalidatedForecasts?user=kingegi&market=us&startdate=08/19/13&enddate=09/12/13

以下是API调用的缩写JSON输出:

[

{
      "Id": "521d992cb031e30afcb45c6c",
      "User": "kingegi",
      "Symbol": "psx",
      "Company": "phillips 66",
      "MarketCap": "34.89B",
      "MCapCategory": "large",
      "Sector": "basic materials",
      "Movement": "up",
      "TimeOfDay": "close",
      "PredictionDate": "2013-08-29T00:00:00Z",
      "Percentage": ".2-.9%",
      "Latency": 37.48089483333333,
      "PickPosition": 2,
      "CurrentPrice": "57.10",
      "ClosePrice": "57.74",
      "HighPrice": null,
      "LowPrice": null,
      "Correct": "FALSE",
      "GainedPercentage": 0,
      "TimeStamp": "2013-08-28T02:31:08 778",
      "ResponseMsg": "",
      "Exchange": "NYSE  "
   },

{
      "Id": "521d992db031e30afcb45c71",
      "User": "kingegi",
      "Symbol": "psx",
      "Company": "phillips 66",
      "MarketCap": "34.89B",
      "MCapCategory": "large",
      "Sector": "basic materials",
      "Movement": "down",
      "TimeOfDay": "close",
      "PredictionDate": "2013-08-29T00:00:00Z",
      "Percentage": "16-30%",
      "Latency": 37.4807215,
      "PickPosition": 1,
      "CurrentPrice": "57.10",
      "ClosePrice": "57.74",
      "HighPrice": null,
      "LowPrice": null,
      "Correct": "FALSE",
      "GainedPercentage": 0,
      "TimeStamp": "2013-08-28T02:31:09 402",
      "ResponseMsg": "",
      "Exchange": "NYSE  "
   }

]

Small Part of code being used:

import os,sys
import subprocess
import glob
from os import path
import urllib2
import json
import time
try:
    data = urllib2.urlopen('http://api.kingegi.com/Api/QuerySystem/GetvalidatedForecasts?user=kingegi&market=us&startdate=08/10/13&enddate=09/12/13').read()
except urllib2.HTTPError, e:
    print "HTTP error: %d" % e.code
except urllib2.URLError, e:
    print "Network error: %s" % e.reason.args[1]
list_id=[x['Id'] for x in data] #test to see if it extracts the ID from each Dict
print(data) #Json output
print(len(data)) #should retrieve the number of dict in list

1 个答案:

答案 0 :(得分:0)

<强>更新

回答了我自己的问题,这是下面的方法:

`url = 'some url that is a list of dictionaries' #GetCall
u = urllib.urlopen(url) # u is a file-like object
data = u.read()
newdata = json.loads(data)
print(type(newdata)) # printed data type will show as a list
print(len(newdata)) #the length of the list
newdict = newdata[1] # each element in the list is a dict
print(type(newdict)) # this element is a dict
length = len(newdata) # how many elements in the list
for a in range(1,length): #a is a variable that increments itself from 1 until a number
    var = (newdata[a])
    print(var['Correct'], var['User'])`