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

iqih9akk  于 2023-06-22  发布在  Ruby
关注(0)|答案(1)|浏览(108)

我需要转换一个字符串如下:

{: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哈希格式的对象,我没有看到一个直接的方法来解析它在Python中。
(to回答问题How to extract value from json in Snowflake

czq61nw1

czq61nw11#

我们可以用一系列正则表达式来解决这个问题:

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

相关问题