JSON文本必须至少包含两个八位字节 [英] A JSON text must at least contain two octets

查看:243
本文介绍了JSON文本必须至少包含两个八位字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到此错误,并且找不到该问题的任何合理答案,因此我想写一个问题的摘要.

I received this error, and I couldn't find any reasonable answer to this question, so I thought I'd write a summary of the problem.

如果您在irb中运行此代码段:

If you run this snippet in irb:

JSON.parse( nil )

您会看到以下错误:

TypeError: can't convert nil into String

我有点希望函数返回nil,而不是TypeError.如果使用to_s转换所有输入,则将看到八位字节错误:

I was kind of expecting the function to return nil, and not a TypeError. If you convert all input using to_s, then you'll see the octet error:

JSON::ParserError: A JSON text must at least contain two octets!

那很好,很好.如果您不知道八位字节是什么,请阅读这篇文章以获取摘要和解决方案: 什么是JSON八位位组,为什么需要两个八位位组?

That's just fine and well. If you don't know what an octet is, read this post for a summary and solution: What is a JSON octet and why are two required?

解决方案

您要传递的变量是一个空字符串.请勿尝试在JSON.parse方法中使用空字符串.

The variable you're passing in is an empty string. Don't attempt to use an empty string in the JSON.parse method.

问题

那么,现在我知道了错误的原因,应该使用哪种模式来处理此错误?我有点讨厌猴子修补JSON库以允许nil值.任何建议将不胜感激.

So, now I know the cause of the error, what pattern should I use to handle this? I'm a bit loathe to monkey patch the JSON library to allow nil values. Any suggestions would be greatly appreciated.

推荐答案

parsed = json && json.length >= 2 ? JSON.parse(json) : nil

但是实际上,库应该能够处理这种情况并返回nil.毕竟,具有内置JSON支持的Web浏览器似乎可以按您期望的那样工作.

But really the library should be able to handle this case and return nil. Web browsers with built-in JSON support seem to work just like you expect after all.

或者只用一个稍微侵入性的迷你补丁来做到这一点:

Or to do it with a only slightly intrusive mini patch:

module JSON
  def self.parse_nil(json)
    JSON.parse(json) if json && json.length >= 2
  end
end

parsed = JSON.parse_nil(json)

这篇关于JSON文本必须至少包含两个八位字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆