这是我的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上迭代,选择我想要的信息并将其放入数组中?
发布于 2015-02-10 19:36:48
您可以使用Array#each,因为data_hash['jobs']包含一个作业数组:
data_hash['jobs'].each {|job| ... }
发布于 2015-02-10 19:44:24
像这样,
arr = Array.new
data_hash.each { |job|
arr.insert(job['name'])
}发布于 2015-02-11 06:05:38
使用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) }
endhttps://stackoverflow.com/questions/28430598
复制相似问题