gpt4 book ai didi

python - 无法像 Python 枚举那样读取 Swift 中返回的 JSON 数组

转载 作者:行者123 更新时间:2023-11-30 11:19:28 25 4
gpt4 key购买 nike

我正在尝试从https://github.com/joshfraser/robinhood-to-csv复制以下Python代码行来自 GitHub 的存储库,以便读取我的交易历史记录。

orders = robinhood.get_endpoint('orders')
paginated = True
page = 0
while paginated:
for i, order in enumerate(orders['results']):
executions = order['executions']
instrument = robinhood.get_custom_endpoint(order['instrument'])
fields[i + (page * 100)]['symbol'] = instrument['symbol']
for key, value in enumerate(order):
if value != "executions":
fields[i + (page * 100)][value] = order[value]
if order['state'] == "filled":
trade_count += 1
for key, value in enumerate(executions[0]):
fields[i + (page * 100)][value] = executions[0][value]
elif order['state'] == "queued":
queued_count += 1
# paginate
if orders['next'] is not None:
page = page + 1
orders = robinhood.get_custom_endpoint(str(orders['next']))
else:
paginated = False

我们也有

def get_endpoint(self, endpoint=None):
res = self.session.get(self.endpoints[endpoint])
return json.loads(res.content.decode('utf-8'))

因此,我一直在编写以下 iOS 代码。我在 XCode Playground 中使用此代码,因此请随意编写一个代码来遵循

import UIKit
import PlaygroundSupport

let LoginEndpoint:String = "https://api.robinhood.com/api-token-auth/"
let LoginRequestData:[String : String] = ["username": "EmailAdress", "password": "Password"]
let OrdersEndpoint:String = "https://api.robinhood.com/orders/"


func httpReq(type: String, url: String, body:[String : String], header:[String : String]) -> ([String : Any]?, Data?, String?){
let url = URL(string: url)
var returnData:([String : Any]?, Data?, String?)? = nil
if let url = url {
var request = NSMutableURLRequest(url: url) as URLRequest
request.httpMethod = type
var postString = ""
for (key, value) in body {
if (postString != "") {
postString += "&"
}
postString += "\(key)=\(value)"
}
request.httpBody = postString.data(using: .utf8)

for (key, value) in header {
request.addValue(value, forHTTPHeaderField: key)
}

let _ = URLSession.shared.dataTask(with: request, completionHandler: {(data, response, error) in
if let data = data {
do {

let jsonSerialized = try JSONSerialization.jsonObject(with: data, options: []) as? [String : Any]
returnData = (jsonSerialized, data, nil)
} catch (_) {
returnData = (nil, data, "JSON Parse Erro")
}
} else if let error = error {
returnData = (nil, nil, error.localizedDescription)
}
}).resume()
}

while (returnData == nil) {}

return returnData!
}

let tokenQuery = httpReq(type: "POST", url: LoginEndpoint, body: LoginRequestData, header: [:])
if let token = tokenQuery.0?["token"] {
print("token \(token)")
let historyQuery = httpReq(type: "GET", url: OrdersEndpoint, body: [:], header: ["Authorization": "Token \(token)"])
if let results = historyQuery.0?["results"], let countString = historyQuery.0?["count"] {
}
}
RunLoop.main.run()
PlaygroundPage.current.needsIndefiniteExecution = true

正如您所看到的,我正在使用身份验证 token 来访问订单端点。我确实从订单端点得到了很好的响应,但我不知道如何解释它。

从Python代码看来,它返回一个JSON对象数组,但是我不知道如何快速访问该数组。我什至不确定我是否正确解码了它。有趣的是,当您查看 Playgrounds 中返回的对象时,XCode 似乎知道存在一个数组。我怎样才能到达它?

最佳答案

由于缺乏凭据,无法真正了解您的服务返回的信息。

但是,请查看SwiftyJSON 。它是一个非常好的库,对于在 Swift 中处理 JSON 数据非常有帮助。它应该可以解决您的 JSON 处理问题。

关于python - 无法像 Python 枚举那样读取 Swift 中返回的 JSON 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51438428/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com