You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Ruby解析多层JSON:无法获取MountPoint键的问题

问题解决:无法获取JSON中的MountPoint键

你的问题出在对JSON结构的理解上:

  • 顶层JSON对象的键确实只有EncryptionStatus和SwitchName,所以json_data.keys只会返回这两个
  • MountPoint是嵌套在EncryptionStatus数组里的每个子对象的键,不是顶层键

正确的访问方式

  1. 先获取EncryptionStatus数组:
    encryption_status_array = json_data["EncryptionStatus"]
    
  2. 遍历数组中的每个对象,提取MountPoint:
    # 获取所有挂载点
    all_mount_points = encryption_status_array.map { |item| item["MountPoint"] }
    # 输出结果: ["C:", "F:", "G:", "H:"]
    
  3. 用dig访问深层值(需要指定数组索引):
    # 获取第一个挂载点
    first_mount_point = json_data.dig("EncryptionStatus", 0, "MountPoint")
    # 输出结果: "C:"
    

完整示例代码

require 'json'

readjson = File.read('your_json_file.json') # 或者直接传入JSON字符串
json_data = JSON.parse(readjson)

# 遍历所有加密状态项
json_data["EncryptionStatus"].each do |status|
  puts "挂载点: #{status["MountPoint"]}, 加密状态: #{status["VolumeStatus"]}"
end

内容的提问来源于stack exchange,提问作者JShlong

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 21:50:31