使用请求及其会话在Python中解析JSON输出

时间:2015-04-13 14:40:28

标签: python json parsing

这里我有一个输出以下内容的费率流,我希望只打印" bid"价钱。有人可以帮助解释我如何正确解析输出?它让我发疯了!

example = 1.05653

我还需要没有引号或任何其他标记的输出..

JSON

{
    "tick": {
        "instrument": "EUR_USD",
        "time": "2015-04-13T14:28:26.123314Z",
        "bid": 1.05653,
        "ask": 1.05669
    }
}

我的代码:

import requests
import json

from optparse import OptionParser

def connect_to_stream():
    """
    Environment           <Domain>
    fxTrade               stream-fxtrade.oanda.com
    fxTrade Practice      stream-fxpractice.oanda.com
    sandbox               stream-sandbox.oanda.com
    """

    # Replace the following variables with your personal ones
    domain = 'stream-fxpractice.oanda.com'
    access_token = 'xxxxx'
    account_id = 'xxxxxxxxx'
    instruments = "EUR_USD"

    try:
        s = requests.Session()
        url = "https://" + domain + "/v1/prices"
        headers = {'Authorization' : 'Bearer ' + access_token,
                   # 'X-Accept-Datetime-Format' : 'unix'
                  }
        params = {'instruments' : instruments, 'accountId' : account_id}
        req = requests.Request('GET', url, headers = headers, params = params)
        pre = req.prepare()
        resp = s.send(pre, stream = True, verify = False)
        return resp
    except Exception as e:
        s.close()
        print "Caught exception when connecting to stream\n" + str(e) 

def demo(displayHeartbeat):
    response = connect_to_stream()
    if response.status_code != 200:
        print response.text
        return
    for line in response.iter_lines(1):
        if line:
            try:
                msg = json.loads(line)
            except Exception as e:
                print "Caught exception when converting message into json\n" + str(e)
                return
                if msg.has_key("instrument") or msg.has_key("tick"):
                    print line                  

            if displayHeartbeat:
                print line
            else:
                if msg.has_key("instrument") or msg.has_key("tick"):
                print line

def main():
    usage = "usage: %prog [options]"
    parser = OptionParser(usage)
    parser.add_option("-b", "--displayHeartBeat", dest = "verbose", action = "store_true", 
                        help = "Display HeartBeat in streaming data")
    displayHeartbeat = False

    (options, args) = parser.parse_args()
    if len(args) > 1:
        parser.error("incorrect number of arguments")
    if options.verbose:
        displayHeartbeat = True
    demo(displayHeartbeat)


if __name__ == "__main__":
    main()

很抱歉,如果这是一个非常基本的问题,但我并不熟悉python ..

提前致谢!

2 个答案:

答案 0 :(得分:0)

尝试以下内容:

def demo(displayHeartbeat):
    response = connect_to_stream()
    for line in response.iter_lines():
        if line.startswith("        \"bid\"")
            print "bid:"+line.split(":")[1]

答案 1 :(得分:0)

您逐行迭代流,尝试将每行解析为JSON。单独的每一行都不是合适的JSON,因此这是一个问题。

我会对你带来的每个hline进行正则表达式寻找文字&#34; bid:&#34;后跟一个十进制数字,并将该数字作为浮点数返回。例如:

import re

for line in response.iter_lines(1):
    matches = re.findall(r'\"bid\"\:\s(\d*\.\d*)', line)
    if len(matches) > 0:
        print float(matches[0])