如何将 Ruby 对象转换为 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3226054/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 22:53:25  来源:igfitidea点击:

How to convert a Ruby object to JSON

ruby-on-railsrubyjson

提问by kapso

I would like to do something like this:

我想做这样的事情:

require 'json'

class Person
attr_accessor :fname, :lname
end

p = Person.new
p.fname = "Mike"
p.lname = "Smith"

p.to_json

Is it possible?

是否可以?

回答by Salil

Yes, you can do it with to_json.

是的,您可以使用to_json.

You may need to require 'json'if you're not running Rails.

require 'json'如果您没有运行 Rails ,则可能需要这样做。

回答by Matchu

Try it. If you're using Ruby on Rails (and the tags say you are), I think this exact code should work already, without requiring anything.

尝试一下。如果您正在使用 Ruby on Rails(并且标签上说您是),我认为这个确切的代码应该已经可以工作了,不需要任何东西。

Rails supports JSON output from controllers, so it already pulls in all of the JSON serialization code that you will ever need. If you're planning to output this data through a controller, you might be able to save time by just writing

Rails 支持来自控制器的 JSON 输出,因此它已经引入了您将需要的所有 JSON 序列化代码。如果您打算通过控制器输出这些数据,您可以通过编写以下代码来节省时间

render :json => @person

回答by Dmitry Shevkoplyas

To make your Ruby class JSON-friendly without touching Rails, you'd define two methods:

为了在不涉及 Rails 的情况下使 Ruby 类对 JSON 友好,您需要定义两个方法:

  • to_json, which returns a JSON object
  • as_json, which returns a hash representation of the object
  • to_json,它返回一个 JSON 对象
  • as_json,它返回对象的哈希表示

When your object responds properly to both to_jsonand as_json, it can behave properly even when it is nested deep inside other standard classes like Array and/or Hash:

当您的对象同时正确响应to_jsonand 时as_json,即使它嵌套在其他标准类(如 Array 和/或 Hash)的深处,它也可以正常运行:

#!/usr/bin/env ruby

require 'json'

class Person

    attr_accessor :fname, :lname

    def as_json(options={})
        {
            fname: @fname,
            lname: @lname
        }
    end

    def to_json(*options)
        as_json(*options).to_json(*options)
    end

end

p = Person.new
p.fname = "Mike"
p.lname = "Smith"

# case 1
puts p.to_json                  # output: {"fname":"Mike","lname":"Smith"}

# case 2
puts [p].to_json                # output: [{"fname":"Mike","lname":"Smith"}]

# case 3
h = {:some_key => p}
puts h.to_json                  # output: {"some_key":{"fname":"Mike","lname":"Smith"}}

puts JSON.pretty_generate(h)    # output
                                # {
                                #   "some_key": {
                                #     "fname": "Mike",
                                #     "lname": "Smith"
                                #   }
                                # }

Also see "Using custom to_json method in nested objects".

另请参阅“在嵌套对象中使用自定义 to_json 方法”。