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

如何将对象数组字符串转换为Ruby哈希数组?

问题:将JSON格式字符串转换为Ruby哈希数组

需求说明

需要将以下格式的Ruby数组(内部是未闭合的JSON对象拼接字符串):

["{
  \"charge_type\": \"sports\",
  \"amount\": 1000
},{
  \"charge_type\": \"servicing\",
  \"amount\": 550
}"]

转换为Ruby哈希数组(注意amount字段为字符串类型):

[{"charge_type"=>"sports", "amount"=> "1000"},{"charge_type"=>"servicing", "amount"=> "550"}]

原尝试代码(失败)

JSON.parse(["{
  \"charge_type\": \"sports\",
  \"amount\": 1000
},{
  \"charge_type\": \"servicing\",
  \"amount\": 550
}"].first)

解决方案

问题原因

原代码失败是因为输入的字符串是两个JSON对象直接拼接,缺少JSON数组必需的外层[],不符合JSON语法规范,导致解析报错。

修正步骤及代码

  1. 取出Ruby数组中的字符串元素,为其添加外层[],构造合法的JSON数组字符串
  2. 使用JSON.parse解析字符串得到哈希数组
  3. 将数组中每个哈希的amount字段从数值转为字符串

完整代码:

require 'json'

# 原始输入
input = ["{
  \"charge_type\": \"sports\",
  \"amount\": 1000
},{
  \"charge_type\": \"servicing\",
  \"amount\": 550
}"]

# 构造合法JSON数组字符串
valid_json_str = "[#{input.first}]"

# 解析JSON并转换amount类型
result = JSON.parse(valid_json_str).map do |item|
  item['amount'] = item['amount'].to_s
  item
end

# 输出结果
p result

执行后将得到目标格式的Ruby哈希数组:

[{"charge_type"=>"sports", "amount"=>"1000"}, {"charge_type"=>"servicing", "amount"=>"550"}]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 23:15:49