Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何将JSON文件解析为Ruby对象_Json_Ruby_Rspec - Fatal编程技术网

如何将JSON文件解析为Ruby对象

如何将JSON文件解析为Ruby对象,json,ruby,rspec,Json,Ruby,Rspec,我尝试创建一个函数,从JSON文件读取并将其解析为对象,给定以下rspec,但它给出了以下错误: NoMethodError:undefined method `from_json' for Recipe:Class 这是lib/recipe.rb: require 'json' class Recipe attr_accessor :title, :description, :ingredients, :cook_time, :featured def initialize(ti

我尝试创建一个函数,从JSON文件读取并将其解析为对象,给定以下rspec,但它给出了以下错误:

NoMethodError:undefined method `from_json' for Recipe:Class
这是lib/recipe.rb:

require 'json'

class Recipe
  attr_accessor :title, :description, :ingredients, :cook_time, :featured

  def initialize(title:, description:, ingredients:, cook_time:, featured:)
    @title = title
    @description = description
    @ingredients = ingredients
    @cook_time = cook_time
    @featured = featured 
  end

  def from_json(file)
    recipe = JSON.parse(json)
    Recipe.new(recipe)
  end
end
我的rspec:

 it 'Converts a json into an objeto from recipe type' do
recipe = Recipe.from_json('data/pudim.json')

    expect(recipe.class).to eq Recipe
    expect(recipe.title).to eq 'Pudim'
    expect(recipe.description).to eq 'O melhor pudim da sua vida!'
    expect(recipe.ingredients).to eq 'Leite condensado, ovos e leite'
    expect(recipe.cook_time).to eq 80
    expect(recipe.featured).to eq true
  end

这是data/pudim.json:

{
  "title": "Pudim",
  "description": "O melhor pudim da sua vida!",
  "ingredients": "Leite condensado, ovos e leite",
  "cook_time": 80,
  "featured": true
}


看起来您正试图调用一个类方法,但您的类中有一个实例方法


有鉴于此,您可以尝试将此方法更改为self.from_jsonfile。

似乎Json.parsejson应该是Json.parsefile。将其更改为Json仍然不起作用