How to convert nested objects to json in ruby?
For example, an object obj contains a custom instance variable b
If you use to_json, the content of b cannot be output.
What is needed is the output of obj.to_s, but if it is in the form of json
It is possible to use to_yaml, but I hope to convert it directly to json
By the way, to_json and to_yaml are obviously the same function. Why is there such a difference in results?
扔个三星炸死你2017-06-08 11:04:01
require 'oj'
class A
def initialize a=[1,2,3], b='hello'
@a = a
@b = b
end
end
puts Oj::dump a, :indent => 2, :mode => :compat
Output:
{
"a":[
1,
2,
3
],
"b":"hello"
}