【问题标题】:Transferring JSON Data into an array using ruby使用 ruby​​ 将 JSON 数据传输到数组中
【发布时间】:2015-02-10 11:32:01
【问题描述】:

这是我的 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​​ 将“工作”列表放入一个数组中。 到目前为止,我有以下代码。

require 'json'
file = File.read(filepath)
data_hash = JSON.parse(file)

如何迭代 data_hash 并选择我想要的信息并将其放入数组中?

【问题讨论】:

  • 使用Hash#each方法迭代。

标签: ruby arrays json


【解决方案1】:

您可以使用Array#each,因为data_hash['jobs'] 包含一组作业:

data_hash['jobs'].each {|job| ... }

【讨论】:

    【解决方案2】:

    这样,

    arr = Array.new
    data_hash.each { |job| 
    arr.insert(job['name'])
    }
    

    【讨论】:

    • 当我使用它时出现以下错误。没有字符串到整数的隐式转换
    • 嗯,试试这个,arr.insert("#{job['name']}")
    【解决方案3】:

    使用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
    

    【讨论】:

      猜你喜欢
      • 2020-12-12
      • 2015-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-05
      • 2015-05-05
      • 2012-01-17
      相关资源
      最近更新 更多