我目前正在 SWIFT 4 中使用 Decodable 解析 JSON。
JSON格式如下:
{
"autopayout_from": "1.010",
"earning_24_hours": "9.74731104",
"error": false,
"immature_earning": 0.635593030875,
"last_payment_amount": "1.91238210",
"last_payment_date": "Mon, 26 Feb 2018 15:08:02 GMT",
"last_share_date": "Mon, 26 Feb 2018 16:16:01 GMT",
"payout_daily": false,
"payout_request": false,
"total_hashrate": 109006.86,
"total_hashrate_calculated": 143855.75,
"transferring_to_balance": 0.2281390807,
"wallet": "0xbb76fc2ce36a19da28fd713e350a42f1023e2f7f",
"wallet_balance": "0.49556201",
"workers": {
"10003": {
"alive": false,
"hashrate": 0.0,
"hashrate_below_threshold": false,
"hashrate_calculated": 0.0,
"last_submit": "Mon, 26 Feb 2018 13:23:16 GMT",
"second_since_submit": 10612,
"worker": "10003"
},
"100151": {
"alive": false,
"hashrate": 0.0,
"hashrate_below_threshold": false,
"hashrate_calculated": 0.0,
"last_submit": "Mon, 26 Feb 2018 09:30:30 GMT",
"second_since_submit": 24578,
"worker": "100151"
},
"100205": {
"alive": true,
"hashrate": 19.28,
"hashrate_below_threshold": true,
"hashrate_calculated": 24.85,
"last_submit": "Mon, 26 Feb 2018 16:12:02 GMT",
"second_since_submit": 486,
"worker": "100205"
},
我能够使用我的结构轻松解析诸如 last_payment_ammount 或 last_payment_date 之类的内容:
struct ticker: Codable{
let error: Bool
let wallet: String
let earning_24_hours: String
let immature_earning: Double
let last_payment_amount: String
let last_payment_date: String
let total_hashrate: Double
let total_hashrate_calculated: Double
let wallet_balance: String
}
我真正费尽心思的是获得嵌套的东西。
例如,我如何使用“worker”变量获取工作人员列表,以便将其放入数组中。或者解析一个 worker 的哈希率值?
非常感谢
最佳答案
下面是我将如何建模:
struct Ticker: Codable {
let autopayoutFrom, earning24_Hours: String
let error: Bool
let immatureEarning: Double
let lastPaymentAmount, lastPaymentDate, lastShareDate: String
let payoutDaily, payoutRequest: Bool
let totalHashrate, totalHashrateCalculated, transferringToBalance: Double
let wallet, walletBalance: String
let workers: [String: Worker]
enum CodingKeys: String, CodingKey {
case autopayoutFrom = "autopayout_from"
case earning24_Hours = "earning_24_hours"
case error
case immatureEarning = "immature_earning"
case lastPaymentAmount = "last_payment_amount"
case lastPaymentDate = "last_payment_date"
case lastShareDate = "last_share_date"
case payoutDaily = "payout_daily"
case payoutRequest = "payout_request"
case totalHashrate = "total_hashrate"
case totalHashrateCalculated = "total_hashrate_calculated"
case transferringToBalance = "transferring_to_balance"
case wallet
case walletBalance = "wallet_balance"
case workers
}
}
struct Worker: Codable {
let alive: Bool
let hashrate: Double
let hashrateBelowThreshold: Bool
let hashrateCalculated: Double
let lastSubmit: String
let secondSinceSubmit: Int
let worker: String
enum CodingKeys: String, CodingKey {
case alive, hashrate
case hashrateBelowThreshold = "hashrate_below_threshold"
case hashrateCalculated = "hashrate_calculated"
case lastSubmit = "last_submit"
case secondSinceSubmit = "second_since_submit"
case worker
}
}
// usage examples:
let ticker = try JSONDecoder().decode(Ticker.self, from: data)
let workerKeys = ticker.workers.keys // "10003", "100151", "100205"
let workers = ticker.workers.values // all workers objects
let alive = workers.filter { $0.alive } // all workers where alive==true
let totalHashrate = alive.reduce(0.0) { $0 + $1.hashrateCalculated }
关于json - 在 SWIFT 4 中解析嵌套的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48993251/
我有一个字符串input="maybe(thisis|thatwas)some((nice|ugly)(day|night)|(strange(weather|time)))"Ruby中解析该字符串的最佳方法是什么?我的意思是脚本应该能够像这样构建句子:maybethisissomeuglynightmaybethatwassomenicenightmaybethiswassomestrangetime等等,你明白了......我应该一个字符一个字符地读取字符串并构建一个带有堆栈的状态机来存储括号值以供以后计算,还是有更好的方法?也许为此目的准备了一个开箱即用的库?
我得到了一个包含嵌套链接的表单。编辑时链接字段为空的问题。这是我的表格:Editingkategori{:action=>'update',:id=>@konkurrancer.id})do|f|%>'Trackingurl',:style=>'width:500;'%>'Editkonkurrence'%>|我的konkurrencer模型:has_one:link我的链接模型:classLink我的konkurrancer编辑操作:defedit@konkurrancer=Konkurrancer.find(params[:id])@konkurrancer.link_attrib
我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i
这道题是thisquestion的逆题.给定一个散列,每个键都有一个数组,例如{[:a,:b,:c]=>1,[:a,:b,:d]=>2,[:a,:e]=>3,[:f]=>4,}将其转换为嵌套哈希的最佳方法是什么{:a=>{:b=>{:c=>1,:d=>2},:e=>3,},:f=>4,} 最佳答案 这是一个迭代的解决方案,递归的解决方案留给读者作为练习:defconvert(h={})ret={}h.eachdo|k,v|node=retk[0..-2].each{|x|node[x]||={};node=node[x]}node[
我正在使用ruby1.9解析以下带有MacRoman字符的csv文件#encoding:ISO-8859-1#csv_parse.csvName,main-dialogue"Marceu","Giveittohimóhe,hiswife."我做了以下解析。require'csv'input_string=File.read("../csv_parse.rb").force_encoding("ISO-8859-1").encode("UTF-8")#=>"Name,main-dialogue\r\n\"Marceu\",\"Giveittohim\x97he,hiswife.\"\
在我的Controller中,我通过以下方式在我的index方法中支持HTML和JSON:respond_todo|format|format.htmlformat.json{renderjson:@user}end在浏览器中拉起它时,它会自然地以HTML呈现。但是,当我对/user资源进行内容类型为application/json的curl调用时(因为它是索引方法),我仍然将HTML作为响应。如何获取JSON作为响应?我还需要说明什么? 最佳答案 您应该将.json附加到请求的url,提供的格式在routes.rb的路径中定义。这
下面例子中的Nested和Child有什么区别?是否只是同一事物的不同语法?classParentclassNested...endendclassChild 最佳答案 不,它们是不同的。嵌套:Computer之外的“Processor”类只能作为Computer::Processor访问。嵌套为内部类(namespace)提供上下文。对于ruby解释器Computer和Computer::Processor只是两个独立的类。classComputerclassProcessor#Tocreateanobjectforthisc
我的假设是moduleAmoduleBendend和moduleA::Bend是一样的。我能够从thisblog找到解决方案,thisSOthread和andthisSOthread.为什么以及什么时候应该更喜欢紧凑语法A::B而不是另一个,因为它显然有一个缺点?我有一种直觉,它可能与性能有关,因为在更多命名空间中查找常量需要更多计算。但是我无法通过对普通类进行基准测试来验证这一点。 最佳答案 这两种写作方法经常被混淆。首先要说的是,据我所知,没有可衡量的性能差异。(在下面的书面示例中不断查找)最明显的区别,可能也是最著名的,是你的
我有一个名为posts的模型,它有很多附件。附件模型使用回形针。我制作了一个用于创建附件的独立模型,效果很好,这是此处说明的View(https://github.com/thoughtbot/paperclip):@attachment,:html=>{:multipart=>true}do|form|%>posts中的嵌套表单如下所示:prohibitedthispostfrombeingsaved:@attachment,:html=>{:multipart=>true}do|at_form|%>附件记录已创建,但它是空的。文件未上传。同时,帖子已成功创建...有什么想法吗?
简而言之错误:NOTE:Gem::SourceIndex#add_specisdeprecated,useSpecification.add_spec.Itwillberemovedonorafter2011-11-01.Gem::SourceIndex#add_speccalledfrom/opt/local/lib/ruby/site_ruby/1.8/rubygems/source_index.rb:91./opt/local/lib/ruby/gems/1.8/gems/rails-2.3.8/lib/rails/gem_dependency.rb:275:in`==':und