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

解析JSON数组后无法访问且data_hash为NilClass,如何实现元素遍历?

解决Ruby解析JSON数组返回NilClass无法遍历的问题

你遇到的核心问题是:读取的文件内容并非纯JSON格式,而是带有变量赋值的JavaScript代码(response = [ ... ]),导致JSON.parse无法正确解析,返回NilClass,因此无法通过索引访问数组或执行遍历操作。

解决方法1:修改源文件为标准JSON格式

直接编辑article_samples.js,做两处修改:

  1. 删除开头的response = ,只保留数组部分
  2. 清理JSON中多余的尾逗号(严格JSON不允许数组/对象最后一个元素后加逗号)

修改后的纯JSON内容如下:

[
  {
    "article" : {
      "info" : {
        "initial" : {
          "articleIds" : [
            "7461221587662919569"
          ]
        }
      },
      "text" : "where they would 'transfer to' next.",
      "lang" : "en"
    }
  },
  {
    "article" : {
      "info" : {
        "initial" : {
          "articleIds" : [
            "6613144915874808065"
          ]
        }
      },
      "text" : "produto regional.",
      "lang" : "pt"
    }
  }
]

之后用Ruby代码正常解析并遍历:

require 'json'
file = File.read('/Users/main/jugg/article_samples.js')
data_array = JSON.parse(file)

# 遍历数组元素
data_array.each do |member|
  puts "文章文本:#{member["article"]["text"]},语言:#{member["article"]["lang"]}"
end

解决方法2:在Ruby代码中动态处理内容(不修改源文件)

如果无法修改源文件,可在读取内容后先预处理,再解析:

require 'json'
file_content = File.read('/Users/main/jugg/article_samples.js')

# 1. 去掉开头的变量赋值语句
json_content = file_content.gsub(/^response\s*=\s*/, '')
# 2. 清理JSON中多余的尾逗号
json_content = json_content.gsub(/,\s*([\]}])/, '\1')

# 解析为数组并遍历
data_array = JSON.parse(json_content)
data_array.each do |member|
  article_id = member["article"]["info"]["initial"]["articleIds"][0]
  puts "文章ID:#{article_id}"
end

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 14:01:38