在Ruby中查找JSON对象内的内容
我有一个JSON对象,如下所示:在Ruby中查找JSON对象内的内容,ruby,json,hash,filter,Ruby,Json,Hash,Filter,我有一个JSON对象,如下所示: [{ "content.app" => { "type" => "content", "depends_on" => [], "primary" => { "id" => 1, "attributes" => { "data" => "my data" }, "meta" => { "schema_version" => "1
[{
"content.app" => {
"type" => "content", "depends_on" => [],
"primary" => {
"id" => 1,
"attributes" => {
"data" => "my data"
},
"meta" => { "schema_version" => "1" }
}
}
}, {
"content.mongodb" => {
"type" => "content", "depends_on" => [],
"primary" => {
"id" => 2,
"attributes" => {
"data" => "my data from app"
}, "meta" => { "schema_version" => "1" }
}
}
}, {
"stuff.other" => {
"type" => "content", "depends_on" => [],
"primary" => {
"id" => 2, "attributes" => {
"data" => "my data from mongodb"
}, "meta" => { "schema_version" => "1" }
}
}
}]
我在寻找这样的结果:
"content.app" => "my data from app",
"content.mongodb" => "my data from mongodb"
如何从所有键(如
content.*
?等)获取属性,一个简单的实现是将每个哈希传递到负责提取它们的类中。比如:
class AttributesExtractor
def initialize(hash)
@hash = hash
@primary_key = hash.keys.first.to_s
end
def extract
return unless primary_key_pattern?
attr_data = hash[primary_key].dig('primary', 'attributes', 'data')
if attr_data
{hash.keys.first => attr_data}
end
end
private
attr_reader :hash, :primary_key
def primary_key_pattern?
primary_key.split('.').first.to_s == 'content'
end
end
the_array_of_hash.map { |hash| AttributesExtractor.new(hash).extract }.compact
=> [{"content.app"=>"my data"}, {"content.mongodb"=>"my data from app"}]
简单的方法是使用inject
和Ruby 2.3的Hash#dig
遍历数据:
data = ... # that array of hashes
data.inject({}){|h,v|
v.inject(h){|h,(k,v)| h[k] = v.dig("primary", "attributes", "data"); h }
h}
# => {"content.app"=>"my data", "content.mongodb"=>"my data from app", "stuff.other"=>"my data from mongodb"}
第一步是使用map
将此结构转换为更接近您所需的结构。欢迎使用堆栈溢出。当询问时,我们希望看到您的努力的一个例子。你在哪里找的?为什么没有帮助?你写了什么代码来解决这个问题?请阅读“”和“”。因此,这不是一个“为我编写代码”的网站,而是一个“帮助我修复我编写的代码”的网站,所以展示你所做的事情是很重要的。有时候每个带有对象({})的\u
都要清楚得多,你不必记得把你的散列串起来。很高兴看到正在使用Hash#dig
!