ruby-on-rails - 在 Ruby 中访问 JSON 对象

标签 ruby-on-rails ruby 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"
              }
            ]
          }
        ]
      }
    }
  ]
}

如何在 ruby​​ 中仅打印域并仅访问 module.names 并将 module.names 打印到控制台:

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

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

有没有人知道适合新手的 ruby​​ 和 json 的任何好的资源?

最佳答案

JSON.parse 接受一个 JSON 字符串并返回一个可以像任何其他操作一样操作的散列 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-on-rails - 在 Ruby 中访问 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29931216/

相关文章:

html - 未显示 Logo 背景图像(Rails 应用程序)

ruby-on-rails - 安全有效地对可能缺失的属性进行排序?

javascript - 显示带有数据库数据的线性 Highcharts

javascript - XML转JSON时为什么在代码中使用 '@attributes'

ruby-on-rails - 由于 ArgumentError : An API Certificate or API Signature is required to make requests to PayPal,Capistrano 和 ActiveMerchant Paypal 将不会部署

ruby-on-rails - Zimbra API 入门

objective-c - "Official"在 Objective-C 中引用类方法的语法?

c# - 将 JSON 字符串反序列化为 C# 复杂类对象

javascript - 下拉菜单不起作用 jQuery 错误

ruby-on-rails - 如何添加条件以在 ActiveAdmin 中显示