在Ruby中访问JSON对象
问题描述:
我有一个看起来像这样的json文件:
I have a json file that looks kind of like this:
{
"Results": [
{
"Lookup": null,
"Result": {
"Paths": [
{
"Domain": "VALUE1.LTD",
"Url": "",
"Text1": "",
"Modules": [
{
"Name": "VALUE",
"Tag": "VALUE",
"FirstDetected": "1111111111",
"LastDetected": "11111111111"
},
{
"Name": "VALUE",
"Tag": "VALUE",
"FirstDetected": "111111111111",
"LastDetected": "11111111111111"
}
]
}
]
}
}
]
}
如何仅打印域并仅在ruby中访问module.name并将其打印到控制台:
How do I print only the domain and access only the module.names in ruby and print the module.names to the console:
#!/usr/bin/ruby
require 'rubygems'
require 'json'
require 'pp'
json = File.read('input.json')
有人知道红宝石和json有什么好的资源吗?
and does any one know of any good resources for ruby and json for someone new to it?
答
JSON.parse
接收JSON字符串并返回一个哈希,该哈希可以像其他任何
JSON.parse
takes a JSON string and return a hash which can be manipulated just like any other hash.
#!/usr/bin/ruby
require 'rubygems'
require 'json'
require 'pp'
# Symbolize keys makes the hash easier to work with
data = JSON.parse(File.read('input.json'), symbolize_keys: true)
# loop through :Results if there are any
data[:Results].each do |r|
# loop through [:Result][:paths] if there are any
r[:Result][:paths].each do |path|
# path refers the current item
path[:Modules].each do |module|
# module refers to the current item
puts module[:name]
end if path[:Modules].any?
end if r[:Result][:paths].any?
end if data[:Results].any?