gpt4 book ai didi

json - 这个 nil 键是如何进入哈希的?

转载 作者:太空宇宙 更新时间:2023-11-03 18:07:21 24 4
gpt4 key购买 nike

我试图实现一个 json 解析器。输入是

"{ \"key\": { \"foo\": \"bar\", \"hello\" : 100 } }"

我格式化成

"{key:{foo:bar,hello:100}}"

然后我将其标记化以获得这样的数组

["{", "key", ":", "{", "foo", ":", "bar", ",", "hello", ":", "100", "}", "}"]

我可能也忽略了 ,。无论如何,当我尝试从该数组构建 ruby​​ 哈希时,我得到了这个

{nil=>{"key"=>{"foo"=>"bar", "hello"=>"100"}}}

我不知道这个 nil 是如何被用作键的。这是我用来构建哈希的方法

def build_hash(arr)
h = {}
keys = []
while arr.size > 0
current_token = arr.shift
if alpha?(current_token)
if keys.empty? # that means a new key is to be expected
keys << current_token
else
h[keys.pop] = current_token
end
elsif current_token == '}'
# these shouldn't be any key left in the keys stack. if there is one, raise error
# otherwise close the hash and return from method
if not keys.empty?
raise_invalid_format_error
else
return h
end
elsif current_token == ','
# continue reading. new key will appear. There shouldn't be any key in keys[]
raise_invalid_format_error unless keys.empty?
elsif current_token == '{'
# this means new hash is starting, nested. Should be a value to a key
# recursive call, assign the result to the existing key
h[keys.pop] = build_hash(arr)
end
end
h
end

如果字符是字母或数字,方法 alpha? 返回 true

def alpha?(s)
s.match(/\A[[:alnum:]]+\z/)
end

这是怎么回事?

最佳答案

数组中的第一个标记将是 { ,这将落入您的最终 elsif案例:

elsif current_token == '{'
# this means new hash is starting, nested. Should be a value to a key
# recursive call, assign the result to the existing key
h[keys.pop] = ....

keys数组为空,所以 pop返回 nil ,您将其用作哈希的键。

关于json - 这个 nil 键是如何进入哈希的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42003546/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com