nil.to_json 无法解析回 nil? [英] nil.to_json cannot be parsed back to nil?

查看:58
本文介绍了nil.to_json 无法解析回 nil?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码段引发异常:

x = nil
jsoned = x.to_json
puts 'x.to_json=' + jsoned.inspect
puts 'back=' + JSON.parse(jsoned).inspect

C:/ruby/lib/ruby/1.9.1/json/common.rb:146:in `parse': 706: unexpected token at 'null'      (JSON::ParserError)
x.to_json="null"
from C:/ruby/lib/ruby/1.9.1/json/common.rb:146:in `parse'
from C:/dev/prototyping/appoxy_app_engine/test/temp.rb:10:in `<top (required)>'
from -e:1:in `load'
from -e:1:in `<main>'

这是预期的行为吗?我认为这应该有效吗?

Is that expected behavior? I would think this should work?

推荐答案

该问题不在于 nil.就是 to_json 在像 nil 这样简单的东西或单个字符串上不会产生完整的 JSON 表示.

The problem is not specifically with nil. It's that to_json on a simple thing like nil or a single string doesn't produce a full JSON representation.

例如类似 JSON.parse("hello".to_json) 会产生类似的结果

e.g. something like JSON.parse("hello".to_json) would yield similar results

如果我们有一个带有 nilHash 作为其值之一,它将正确编码和解码:

If we have a Hash with nil for one of its values it will encode and decode correctly:

>> h = {"name"=>"Mike", "info"=>nil}
=> {"name"=>"Mike", "info"=>nil}
>> h.to_json
=> "{\"name\":\"Mike\",\"info\":null}"
>> JSON.parse(h.to_json)
=> {"name"=>"Mike", "info"=>nil}

这篇关于nil.to_json 无法解析回 nil?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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