Ruby-on-rails 什么是 JSON 八位字节,为什么需要两个?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7200554/
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
What is a JSON octet and why are two required?
提问by MorningHacker
I have incoming data, which I store in a variable messages:
我有传入的数据,我将其存储在一个变量中messages:
connection = ContextIO::Connection.new(key, secret)
messages = connection.all_messages(:account => account, :limit => 100, :since => (Time.now - 3000.day ))
The variable messagesis formatted in JSON. Then I execute this:
该变量messages采用 JSON 格式。然后我执行这个:
foo = JSON.parse(messages)['data']
Most of the time this works. Every now and again, I get this error message:
大多数时候这是有效的。时不时地,我收到此错误消息:
A JSON text must at least contain two octets!
That error message then refers to the line JSON.parse(messages)['data']
该错误消息然后指的是该行 JSON.parse(messages)['data']
What is an octet?
Why must JSON text contain at least two octets?
How do I prevent my code from breaking every time
messagesdoes not have two octets?
什么是八位字节?
为什么 JSON 文本必须至少包含两个八位字节?
每次
messages没有两个八位字节时,如何防止我的代码被破坏?
Thanks!
谢谢!
回答by phihag
- An octet is a group of 8 bits. Today, octet is synonymous with byte, but byte historically referred to any "native" grouping of bits, and that could mean 4,6,7, or 8 bits.
- JSON text must contain at least two octets because the top-level structure of a JSON document is an array or object, and the shortest representations of those are
[]and{}, respectively. - Check the value
messages. It is probably empty, unset or consists of a single digit (like4), which is notvalid JSON, but accepted by many JSON implementations.
- 八位字节是一组 8 位。今天,八位字节是字节的同义词,但字节在历史上指的是任何“本机”位分组,这可能意味着 4、6、7 或 8 位。
- JSON 文本必须至少包含两个八位字节,因为 JSON 文档的顶级结构是数组或对象,它们的最短表示分别是
[]和{}。 - 检查值
messages。它可能为空、未设置或由单个数字(如4)组成,这不是有效的 JSON,但被许多 JSON 实现接受。
回答by Stephen Moore
While I totally agree with the other answer, in my case I had a valid JSONstring but was still receiving the "JSON text must contain at least two octets" error message when trying to JSON.parse.
虽然我完全同意另一个答案,但在我的情况下,我有一个有效的JSON字符串,但在尝试JSON.parse.
My issue was that I was not specifying content type of application/json. Once I added that, JSON.parseworked without error.
我的问题是我没有指定application/json. 一旦我添加了它,就可以正常JSON.parse工作。
Hope this helps someone else.
希望这对其他人有帮助。

