简体   繁体   English

JSON数组散列

[英]JSON Array to Hash

I need to parse and display solr facets which are returned in either JSON or Ruby formar: 我需要解析并显示以JSON或Ruby formar返回的Solr构面:

Collections: [ "a", 1, "b", 2, "c", 3, "d", 4, ... ] 集合:[“ a”,1,“ b”,2,“ c”,3,“ d”,4,...]

into 进入

{"a"=>1, "b"=>2, "c"=>3, "d"=>4} 

What is the cleanest way? 什么是最干净的方法?

EDIT: Well now that we know what you actually want, a hash ... 编辑:现在我们知道您真正想要的是什么, hash ...

collections = ["a", 1, "b", 2, "c", 3, "d", 4]
Hash[*collections]
# => {"a"=>1, "b"=>2, "c"=>3, "d"=>4} 

Original answer : I may not understand your goal but... 原始答案 :我可能不明白您的目标,但是...

collections = ["a", 1, "b", 2, "c", 3, "d", 4]
collections.each_slice(2).map{ |(x, y)| "#{x} - #{y}" }
# => ["a - 1", "b - 2", "c - 3", "d - 4"]

What i see you want to do is maybe a hash ? 我看到您要执行的操作可能是哈希值? {a => "1", b => "2"} ?? {a =>“ 1”,b =>“ 2”} ??

If so, read below: 如果是这样,请阅读以下内容:

collections = [ "a", 1, "b", 2, "c", 3, "d", 4]


result = Hash[*collections.flatten]

result prints {"a"=>1, "b"=>2, "c"=>3, "d"=>4} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM