I'm trying to understand the JSON serialization landscape in Ruby. I'm new to Ruby.
我试图理解Ruby中的JSON序列化场景。我新Ruby。
Is there any good JSON serialization options if you are not working with Rails?
如果不使用Rails,有什么好的JSON序列化选项吗?
That seems to be where this answer goes (to Rails) How to convert a Ruby object to JSON
这似乎就是这个问题的答案(Rails)如何将Ruby对象转换为JSON。
The json gem seems to make it look like you have to write your own to_json method. I haven't been able to get to_json to work with arrays and hashes (documentation says it works with these) Is there a reason the json gem doesn't just reflect over the object and use a default serialization strategy? Isn't this how to_yaml works (guessing here)
json gem似乎要编写自己的to_json方法。我还没能让to_json使用数组和散列(文档说明它与这些文件一起工作),为什么json gem不只是对对象进行反射,并使用默认的序列化策略?to_yaml不是这样工作的吗?
11 个解决方案
#1
100
For the JSON library to be available, you may have to install libjson-ruby
from your package manager.
要想获得JSON库,您可能需要从包管理器中安装libjson-ruby。
To use the 'json' library:
使用“json”库:
require 'json'
To convert an object to JSON (these 3 ways are equivalent):
将对象转换为JSON(这三种方式是等价的):
JSON.dump object #returns a JSON string
JSON.generate object #returns a JSON string
object.to_json #returns a JSON string
To convert JSON text to an object (these 2 ways are equivalent):
将JSON文本转换为对象(这两种方式是等效的):
JSON.load string #returns an object
JSON.parse string #returns an object
It will be a bit more difficult for objects from your own classes. For the following class, to_json will produce something like "\"#<A:0xb76e5728>\""
.
对于来自您自己的类的对象来说,这将会更加困难一些。对于下面的类,to_json将生成类似“\”# <0xb76e5728>0xb76e5728>
>>
>
>>
#1
100
For the JSON library to be available, you may have to install libjson-ruby
from your package manager.
要想获得JSON库,您可能需要从包管理器中安装libjson-ruby。
To use the 'json' library:
使用“json”库:
require 'json'
To convert an object to JSON (these 3 ways are equivalent):
将对象转换为JSON(这三种方式是等价的):
JSON.dump object #returns a JSON string
JSON.generate object #returns a JSON string
object.to_json #returns a JSON string
To convert JSON text to an object (these 2 ways are equivalent):
将JSON文本转换为对象(这两种方式是等效的):
JSON.load string #returns an object
JSON.parse string #returns an object
It will be a bit more difficult for objects from your own classes. For the following class, to_json will produce something like "\"#<A:0xb76e5728>\""
.
对于来自您自己的类的对象来说,这将会更加困难一些。对于下面的类,to_json将生成类似“\”# <0xb76e5728>0xb76e5728>
>>
>
>>