/ / रूबी में JSON ऑब्जेक्ट्स को एक्सेस करना [बंद] - रूबी-ऑन-रेल, रूबी, json

रुबी में बंद JSON ऑब्जेक्ट्स तक पहुंच [बंद] - रूबी-ऑन-रेल, रूबी, जेसन

मेरे पास एक json फ़ाइल है जो इस तरह की दिखती है:

{
"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"
}
]
}
]
}
}
]
}

मैं केवल डोमेन कैसे प्रिंट करूं और रूबी में केवल मॉड्यूल.नाम का उपयोग करूं और मॉड्यूल.नाम को कंसोल में प्रिंट करूं:

#!/usr/bin/ruby
require "rubygems"
require "json"
require "pp"

json = File.read("input.json")

और क्या किसी को माणिक और जोंस के लिए किसी अच्छे संसाधन का पता है?

उत्तर:

उत्तर № 1 के लिए 6

JSON.parse एक JSON स्ट्रिंग लेता है और एक हैश लौटाता है जिसे किसी भी अन्य की तरह ही हेरफेर किया जा सकता है हैश.

#!/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?

जवाब के लिए 3 № 2

रूबी में आपको हैश तक पहुंचने के लिए चौकोर कोष्ठक का उपयोग करना पड़ता है।

json =JSON.parse(File.read("input.json"))
domains = []
json.Results.map{|result| result.Paths.map{|path| domains << path.Domain }}

हालाँकि यह रूबी है ... तो आप भी हैश क्लास को ओवरराइड कर सकते हैं और एक साधारण डॉट नोटेशन के साथ अपने हैश को एक्सेस कर सकते हैं। (सरल समाधान द्वारा: @papirtiger) उदाहरण के लिए: डोमेन = json.Results.Paths.Domain

require "ostruct"
JSON.parse(File.read("input.json"), object_class: OpenStruct)

उत्तर № 3 के लिए 1

तुम कोशिश कर सकते हो:

json_file = JSON.parse(File.read("input.json"))

json_file[:Results].each {|y| y[:Result][:Paths].each do |a|
puts "Domain names: #{a[:Domain]}"
a[:Modules].each {|b| puts "Module names are: #{b[:Name]}" }
end
}

#=> Domain names: VALUE1.LTD
#=> Module names are: VALUE
#=> Module names are: VALUE