尝试从ruby创建json对象

  • 本文关键字:json 对象 创建 ruby ruby
  • 更新时间 :
  • 英文 :


我正在尝试在Ruby中创建此字符串。

{
quantity: 1,
discount_type: :dollar,
discount_amount: 0.01,
discount_message: 'this is my message',
}

通过阅读类,我可以看到我可以像这样初始化它:

class DiscountDisplay
def initialize(quantity, type, amount, message)
@quantity = quantity
@discount_type = type
@discount_amount = amount
@discount_message = message
end
end
f = DiscountDisplay.new( 1, :dollar, 0.01, 'this is my message' )

如何创建json字符串?没有使用要求'json'其他人已经在其他一些答案中指出。

我会像这样添加to_json方法到DiscountDisplay类:

class DiscountDisplay
require 'json'
def initialize(quantity, type, amount, message)
# ...
end
def to_json
JSON.generate(
quantity: @quantity,
discount_type: @discount_type,
discount_amount: @discount_amount,
discount_message: @discount_message,
)
end
end

然后这样命名:

discount_display = DiscountDisplay.new(1, :dollar, 0.01, 'this is my message')
discount_display.to_json
#=> '{"quantity":1,"discount_type":"dollar","discount_amount":0.01,"discount_message":"this is my message"}'

最新更新