这是我的JSON代码
{
"jobs": [
{
"id": 1,
"title": "Software Developer",
"applicants": [
{
"id": 1,
"name": "Rich Hickey",
"tags": ["clojure", "java", "immutability", "datomic", "transducers"]
},
{
"id": 2,
"name": "Guido van Rossum",
"tags": ["python", "google", "bdfl", "drop-box"]
}
]
},
{
"id": 2,
"title": "Software Architect",
"applicants": [
{
"id": 42,
"name": "Rob Pike",
"tags": ["plan-9", "TUPE", "go", "google", "sawzall"]
},
{
"id": 2,
"name": "Guido van Rossum",
"tags": ["python", "google", "bdfl", "drop-box"]
},
{
"id": 1337,
"name": "Jeffrey Dean",
"tags": ["spanner", "BigTable", "MapReduce", "deep learning", "massive clusters"]
}
]
}
]
}
我想使用ruby将“Jobs”列表放在一个数组中。 到目前为止,我有以下代码。
require 'json'
file = File.read(filepath)
data_hash = JSON.parse(file)
如何迭代data_hash并选择我想要的信息并将其放入数组?
答案 0 :(得分:0)
您可以使用Array#each
,因为data_hash['jobs']
包含一系列作业:
data_hash['jobs'].each {|job| ... }
答案 1 :(得分:0)
像这样,
arr = Array.new
data_hash.each { |job|
arr.insert(job['name'])
}
答案 2 :(得分:0)
使用Array#map
代码更短
data_hash['jobs'].map do |job|
# Do whatever you want with the job here
properties = %w(title applicants)
job.select{ |key| properties.include?(key) }
end