How to convert a ruby hash object to JSON? So I am trying this example below & it doesn't work?

I was looking at the RubyDoc and obviously Hash object doesn't have a to_json method. But I am reading on blogs that Rails supports active_record.to_json and also supports hash#to_json. I can understand ActiveRecord is a Rails object, but Hash is not native to Rails, it's a pure Ruby object. So in Rails you can do a hash.to_json, but not in pure Ruby??

car = {:make => "bmw", :year => "2003"}
car.to_json

推荐答案

One of the numerous niceties of Ruby is the possibility to extend existing classes with your own methods. That's called "class reopening" or monkey-patching (the meaning of the latter can vary, though).

那么,看看这里:

car = {:make => "bmw", :year => "2003"}
# => {:make=>"bmw", :year=>"2003"}
car.to_json
# NoMethodError: undefined method `to_json' for {:make=>"bmw", :year=>"2003"}:Hash
#   from (irb):11
#   from /usr/bin/irb:12:in `<main>'
require 'json'
# => true
car.to_json
# => "{"make":"bmw","year":"2003"}"

As you can see, requiring json has magically brought method to_json to our Hash.

Json相关问答推荐

jq不会为空输入返回非零

Jolt变换将字段移动到数组的每个元素中

无法从JSON解析ZonedDateTime,但可以使用格式化程序很好地解析

重构JOLT代码以获得预期输出

在Snowflake中查询JSON时,属性名称是否支持绑定参数?

从包含 JSON 对象序列的文件中获取第一个 JSON 对象

Jolt 不打印任何东西

Golang gin接收json数据和图片

在 CodePipeline 中调用 lambda 时传递用户参数

如何在 Android Studio 中将 List 字段作为空列表[]返回?

无法向 Json 数组添加新元素

使用基本身份验证通过 CURL 发布 JSON

如何使用法语口音对数组进行 json_encode?

数据包含连续问号时无法理解的 jQuery $.ajax() 行为

如何使用 SwiftyJSON 将字符串转换为 JSON

如何按键查找特定的 JSON 值?

运算符不存在:json = json

如何使用 SwiftyJSON 遍历 JSON?

类型是接口或抽象类,不能实例化

无法将 System.String 转换或转换为 Class 对象