如何将对象数组字符串转换为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语法规范,导致解析报错。
修正步骤及代码
- 取出Ruby数组中的字符串元素,为其添加外层
[],构造合法的JSON数组字符串 - 使用
JSON.parse解析字符串得到哈希数组 - 将数组中每个哈希的
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
相关产品推荐
相关产品推荐

