首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Ruby中的JSON数据到实例变量

Ruby中的JSON数据到实例变量
EN

Stack Overflow用户
提问于 2015-02-12 11:56:03
回答 2查看 4K关注 0票数 0

这是我的红宝石代码/ JSON文件。需要三种功能,我已经实现了前两种,但第三种功能有问题。我只是最近才开始学习ruby -任何简单的解释/答案都是非常感谢的。

代码语言:javascript
复制
class Company
  attr_accessor :jobs
  jobs = Array.new 

  ## TODO: Implement this method to load the given JSON file into Ruby built-in data
  ## structures (hashes and arrays).
  def self.load_json(filepath)
    require 'json'
    file = File.read(filepath)
    data_hash = JSON.parse(file)
  end

  ## TODO: This method should update the `jobs` property to an array of instances of
  ## class `Job`
  def initialize(filepath)
    # Load the json file and loop over the jobs to create an array of instance of `Job`
    # Assign the `jobs` instance variable.
    load_json(filepath)
    data_hash.each { |jobs|
    array_of_jobs.insert(jobs['name'])
    }
  end

  ## TODO: Impelement this method to return applicants from all jobs with a
  ## tag matching this keyword
  def find_applicants(keyword)
    # Use the `jobs` instance variable.

  end
end

下面是我应该从其中检索信息的JSON文件代码。

代码语言:javascript
复制
{
  "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"]
        }
      ]
    }
  ]
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-02-12 17:16:51

您提供的代码不会编译,使用的方法也不太方便。您可以按照以下步骤来实现它:

首先实现您的模型。看起来可能是:

代码语言:javascript
复制
class Applicant
  attr_accessor :id, :name, :tags

  def initialize(id, name=nil, tags=nil)
    @id = id
    @name = name
    @tags = tags
  end
end

class Job
  attr_accessor :id, :title, :applicants

  def initialize(id, title=nil, applicants=nil)
    @id = id
    @title = title
    @applicants = applicants
  end
end

然后定义与作业一起工作的公司类

代码语言:javascript
复制
class Company
  attr_accessor :jobs

  def initialize(jobs)
    @jobs = jobs
  end

  def find_applicants(keyword)
    # Now you can iterate through jobs, 
    # job's applicants and finally applicant's tags
    # like this
    applicants = []
    @jobs.each do |job|
      job.applicants.each do |applicant|
        applicant.tags.each do |tag|
          if keyword.eql? tag
             # ...
          end
        end
      end
    end
    applicants
  end
end

然后可以从Json文件加载数据并构造适当的对象:

代码语言:javascript
复制
require 'json'

class DataLoader
  def load(filepath)
    hash = JSON.parse(filepath)
    construct(hash)
  end

  private

  def validate(hash)
    # validate your data here
  end

  def construct(hash)
    validate(hash)
    jobs = []
    hash['jobs'].each do |job|
      applicants = []
      job['applicants'].each do |applicant|
        applicants << Applicant.new(applicant['id'], applicant['name'], applicant['tags'])
      end
      jobs << Job.new(job['id'], job['title'], applicants)
    end
    jobs
  end
end

所有这些都会看起来像:

代码语言:javascript
复制
tag = 'google'

data = DataLoader.new.load(File.read('data.json'))
company = Company.new(data)
applicants = company.find_applicants(tag)

puts "Applicants that have '#{tag}' in taglist"
applicants.each do |applicant|
  puts "  #{applicant.id}: #{applicant.name}"
end

#Applicants that have google in taglist
#  2: Guido van Rossum
#  42: Rob Pike
票数 2
EN

Stack Overflow用户

发布于 2015-02-12 16:09:42

下面是find_applicants的一个简单实现。JSON对象可以像任何其他数据结构一样被迭代。

这里有一个例子

代码语言:javascript
复制
def find_applicants(myJson, keyword)
    names = []
    myJson["jobs"].each do |job|

        job["applicants"].each do |applicant|
           tags = applicant["tags"]
           if tags.include? keyword then
               names << applicant["name"]
           end  
        end
    end
    names
end
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28476831

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档