简体   繁体   English

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

[英]Parse JSON output in Python using Requests and its sessions

Here I have a rate stream that outputs the following and i'm looking to only print the "bid" price. 在这里,我有一个输出以下内容的费率流,我希望仅打印“出价”价格。 Could someone help explain how I can parse the output correctly? 有人可以帮忙解释一下我如何正确解析输出吗? It's driving me crazy! 这让我疯狂!

example = 1.05653 示例= 1.05653

I need the output without quotes or any other markup as well.. 我需要不带引号或其他任何标记的输出。

JSON JSON

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

My code: 我的代码:

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

Sorry if this is an extremely basic question but I'm not that familiar with python.. 抱歉,如果这是一个非常基本的问题,但是我对python不太熟悉。

Thanks in advance! 提前致谢!

Try something along the lines of this: 尝试一些类似的方法:

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

You are iterating over the stream line by line attempting to parse each line as JSON. 您正在逐行迭代流,尝试将每行解析为JSON。 Each line alone is not proper JSON so that's one problem. 单独的每一行都不是正确的JSON,所以这是一个问题。

I would just regex over each hline you bring in looking for the text "bid: " followed by a decimal number, and return that number as a float. 我只需要对输入的每个hline进行正则表达式查找文本“ bid:”,后跟一个十进制数字,然后将该数字作为浮点数返回即可。 For example: 例如:

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

This actually turned out to be pretty easy, I fixed it by replacing the "demo" function with this: 事实证明,这非常简单,我通过用以下示例替换“ demo”函数来修复它:

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 displayHeartbeat:
                print line
            else:
                if msg.has_key("instrument") or msg.has_key("tick"):
                    print msg["tick"]["ask"] - .001
                    instrument = msg["tick"]["instrument"]
                    time = msg["tick"]["time"]
                    bid = msg["tick"]["bid"]
                    ask = msg["tick"]["ask"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM