使用Ruby解析多层JSON:无法获取MountPoint键的问题
问题解决:无法获取JSON中的MountPoint键
你的问题出在对JSON结构的理解上:
- 顶层JSON对象的键确实只有
EncryptionStatus和SwitchName,所以json_data.keys只会返回这两个 MountPoint是嵌套在EncryptionStatus数组里的每个子对象的键,不是顶层键
正确的访问方式
- 先获取
EncryptionStatus数组:encryption_status_array = json_data["EncryptionStatus"] - 遍历数组中的每个对象,提取
MountPoint:# 获取所有挂载点 all_mount_points = encryption_status_array.map { |item| item["MountPoint"] } # 输出结果: ["C:", "F:", "G:", "H:"] - 用
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
相关产品推荐
相关产品推荐

