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

如何用Python将Ruby哈希字符串转换为JSON字符串?

将Ruby哈希字符串转换为JSON的Python实现

核心差异与处理步骤

要把Ruby哈希转成JSON,需要修正三类语法/格式差异:

  1. 键格式:将Ruby的:key=>value替换为JSON标准的"key":value
  2. 空值:把Ruby的nil替换为JSON的null
  3. 日期对象:将Ruby的日期字符串(如Mon, 15 May 2023)转换为ISO 8601格式的字符串(如"2023-05-15")

代码实现

import re
from datetime import datetime
import json

def ruby_hash_to_json(ruby_str):
    # 替换Ruby符号键为JSON键格式
    processed = re.sub(r':(\w+)=>', r'"\1":', ruby_str)
    # 替换Ruby的nil为JSON的null
    processed = processed.replace('nil', 'null')
    # 转换Ruby日期格式为ISO字符串
    def convert_date_match(match):
        date_str = match.group(0)
        dt = datetime.strptime(date_str, '%a, %d %b %Y')
        return f'"{dt.date().isoformat()}"'
    processed = re.sub(r'\w{3}, \d{2} \w{3} \d{4}', convert_date_match, processed)
    # 解析为JSON并格式化输出
    return json.dumps(json.loads(processed), indent=2)

# 测试示例
ruby_hash_str = '{:old_id=>{:id=>"12345", :create_date=>Mon, 15 May 2023, :amount=>50.0}, :new_id=>{:id=>nil, :create_date=>"2023-05-15", :amount=>"50.00"}}'
print(ruby_hash_to_json(ruby_hash_str))

输出结果

{
  "old_id": {
    "id": "12345",
    "create_date": "2023-05-15",
    "amount": 50.0
  },
  "new_id": {
    "id": null,
    "create_date": "2023-05-15",
    "amount": "50.00"
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 03:15:11