1. 程式人生 > >python網路請求將json字元轉為物件

python網路請求將json字元轉為物件


class CreateOrder:
    def __init__(self):
        self.code
        self.data
        self.msg


#	做多(0)、做空(1)
def reqCreateOrderAndEditOrder():
    createOrder_url = "/mt4/createOrder"
    cmd = "0"
    #	品質
    symbol = "XAUUSD.fix"
    mt4id = "800016"
    volume = "0.01"
    tp = "0"
    sl = "0"
    param = "?cmd=" + cmd + "&symbol=" + symbol + "&mt4id=" + mt4id + "&volume=" + volume + "&tp=" + tp + "&sl=" + sl
    # param="?cmd=0&symbol=UT100.fix&mt4id=800016&volume=1.0&tp=0&sl=0"
    # param="?cmd=0&symbol=UKOil.fix&mt4id=800016&volume=1.0&tp=0&sl=0"
    # param="?cmd=0&symbol=EURUSD.fix&mt4id=800016&volume=1&tp=0&sl=0"
    print("下單介面")
    createOrder_url = host + createOrder_url + param
    html = urllib.request.urlopen(createOrder_url)

    myjsonstr = html.read().decode('utf-8')

    print(myjsonstr)

    # json轉化為字典
    myClassReBuild = json.loads(myjsonstr)
    # 列印重建的字典
    print(myClassReBuild)
    # 新建一個新的MyClass物件
    myClass2 = CreateOrder()
    # 將字典轉化為物件
    myClass2.__dict__ = myClassReBuild
    # 列印重建的物件
    print(myClass2.data)
    ######################################################################################################

    # 修改訂單

    #	做多(0)、做空(1)
    createOrder_url = "/mt4/updateOrder"
    cmd = "0"
    #	品質
    mt4id = "800016"
    tp = "1300.2"
    sl = "1110.0"
    ticket = myClass2.data
    price = myClass2.msg
    param = "?cmd=" + cmd + "&symbol=" + symbol + "&mt4id=" + mt4id + "&volume=" + volume + "&tp=" + tp + "&sl=" + sl + "&ticket=" + ticket + "&price=" + price
    print("修改訂單介面")
    createOrder_url = host + createOrder_url + param
    html = urllib.request.urlopen(createOrder_url)
    print(html.read().decode('utf-8'))