在Ruby中访问JSON对象 [英] Accessing JSON objects in Ruby

查看:300
本文介绍了在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?

这篇关于在Ruby中访问JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆