提问人:Felipe Hoffa 提问时间:6/21/2023 更新时间:6/21/2023 访问量:64
如何使用 Python 将 Ruby 哈希字符串转换为 JSON 字符串?
How do I convert a Ruby hash string into a JSON string using Python?
问:
我需要转换一个字符串,例如:
{: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"}}
在 Python 中转换为 JSON 字符串。
这似乎是一个 Ruby Hash 格式的对象,我没有看到在 Python 中解析它的直接方法。
答:
0赞
Felipe Hoffa
6/21/2023
#1
我们可以用一系列正则表达式来解决这个问题:
import re
def ruby_hash_to_json(input_str):
input_str = input_str.replace('=>', ':')
input_str = input_str.replace(':nil', ':null') # JSON uses null, not None
# Remove weekday from date string and add quotes around date
input_str = re.sub(r'\w+, (\d{2} \w{3} \d{4})', r'"\1"', input_str)
# Convert Ruby's symbols (words preceded by a colon) into valid JSON keys (quoted words)
# This handles symbols both at the beginning of the string and in other positions.
input_str = re.sub(r'({|, ):(\w+)', r'\1"\2"', input_str)
return input_str
下一个:如何运行以下 ruby 项目?
评论
Hash
Hash
inspect
p