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

Ruby中解析Open3.popen3输出含JSON内容的问题

解决Ruby中解析非标准JSON(单引号)的问题

你的问题核心是命令输出的JSON使用了单引号,而Ruby的JSON.parse只支持符合RFC 8259的标准JSON(要求键和字符串值必须用双引号),同时原代码的字符串提取方式未处理好换行和多余内容。以下是规范的解决步骤:

步骤1:精准提取JSON部分

命令输出包含日志文本和JSON数组两行内容,通过正则匹配可以准确提取从[开始到]结束的完整JSON结构,避免手动截取的误差:

stdout_content = stdout.read
# 多行正则匹配完整的JSON数组(m修饰符允许.匹配换行符)
json_match = stdout_content.match(/(\[.*\])/m)
raise "No valid JSON array found in command output" unless json_match
json_str = json_match[1]

步骤2:转换为标准JSON格式

将非标准的单引号替换为双引号,确保符合JSON规范:

# 全局替换所有单引号为双引号(如果输出字符串内部无单引号冲突,此方法足够简洁)
json_str = json_str.gsub("'", '"')

如果输出的字符串值中可能包含单引号(比如{'name': "O'Neil"}),可以用更精准的正则分别替换键和值的单引号:

# 替换键的单引号:'key': → "key":
json_str = json_str.gsub(/'(\w+)':/, '"\1":')
# 替换值的单引号:'value' → "value"
json_str = json_str.gsub(/: '([^']*)'/, ': "\1"')

步骤3:解析JSON

完成格式转换后,即可正常使用JSON.parse解析:

list = JSON.parse(json_str)

完整代码示例

_, stdout, stderr, wait_thr = Open3.popen3("<command>")
raise "<command> failed: #{stderr.read}" if wait_thr.value != 0

stdout_content = stdout.read
json_match = stdout_content.match(/(\[.*\])/m)
raise "No valid JSON array found in command output" unless json_match

json_str = json_match[1].gsub("'", '"')
list = JSON.parse(json_str)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 17:58:07