json - 为什么marshaling可以序列化循环引用列表而json不可以?

标签 json ruby serialization marshalling circular-reference

这里我有一个循环引用列表

2.1.9 :082 > a = []
 => [] 
2.1.9 :083 > a.append(a)
 => [[...]] 

当尝试将 a 转储为 json 时,出现错误

a.to_json
ActiveSupport::JSON::Encoding::CircularReferenceError: object references itself

但是当我尝试编码它们时,我得到了一个有效的字符串

2.1.9 :085 > Marshal.dump(a)
 => "\x04\b[\x06@\x00" 

我只是试图通过再次加载它们来确保它们正确地转储了值

 b = Marshal.load("\x04\b[\x06@\x00")
 => [[...]] 

这里有一些验证,以确保他们正确地将对象转储到字符串

2.1.9 :088 > a.object_id
 => 70257482733700 
2.1.9 :089 > a.first.object_id
 => 70257482733700 
2.1.9 :090 > b.object_id
 => 70257501553000 
2.1.9 :091 > b.first.object_id
 => 70257501553000 
2.1.9 :092 > 

据我了解,它们都是将对象转换为字符串,然后从字符串中取回对象。我还可以看到 json 没有任何构造来引用 json 的其他部分,这可能是它不支持这种操作的原因。但是在 json 中引入这样的构造来促进当前的情况是不是很困难。我可能遗漏了一些关于编码和序列化的更基本的东西,请赐教。

最佳答案

In my understanding both of them are converting an object to string and get the object back from the string.

是的。这几乎就是“序列化”或“编码”的定义。

I also able to see that json don't have any construct to refer other part of the json which may be the reason why it can't support this kind of operation.

是的,就是这个原因。

But is it that difficult to introduce such construct in json to facilitate the current situation.

您不能在 JSON 中引入结构.它被特意设计为没有版本号,因此永远无法更改。

当然,这仅意味着我们不能现在添加它,但是 Doug Crockford 是否可以从一开始就添加它,回到他设计 JSON 的时候?是的当然。但他没有。 JSON was deliberately designed to be simple (bold emphasis mine) :

JSON is not a document format. It is not a markup language. It is not even a general serialization format in that it does not have a direct representation for cyclical structures […]

参见,例如,YAML ,JSON 的超集,它具有引用,因此可以表示循环数据。

关于json - 为什么marshaling可以序列化循环引用列表而json不可以?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41445062/

相关文章:

Ruby Fiddle dll 搜索路径

c# - 在 C# 中序列化泛型类

asp.net - json 响应包含\n\r

json - 如何获取主键相关字段嵌套序列化程序 django rest 框架的所有值

javascript - .js 文件和 jQuery AJAX 方法

json - 如何在 XE4 中使用 TFDJSONDataSets 或类似的?

php - JSON值编码两次: how to use fetch_assoc()?

ruby - 快速检查数组是否相交

ruby - 如何使用 Ruby 有效地匹配来自 2 个数组的数据

Swift Playground 中没有输出的 JSONDecoder