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

How do I convert a Ruby hash string into a JSON string using Python?

提问人:Felipe Hoffa 提问时间:6/21/2023 更新时间:6/21/2023 访问量:64

问:

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

{: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 中解析它的直接方法。

(回答问题如何在 Snowflake 中从 json 中提取价值)

Python Ruby 解析

评论

8赞 Amadan 6/21/2023
它甚至不是 Ruby 格式的,它是 Ruby 的输出;如果你把它输入到 Ruby 中,它会在日期上窒息。无论谁在数据库中记录了这一点,都应该重新考虑他们的生活选择。:PHashHash
0赞 Holger Just 6/21/2023
您应该强烈尝试不要解析此字符串,而是尝试更改此字符串的创建方式。这看起来像是调用 Ruby Hash 的结果(例如,通过将格式化对象输出到 STDOUT 的方法隐式调用)。如果你想用代码来使用这个输出,你应该改变你的 Ruby 程序,例如发出 JSON,然后你可以在 Python 中轻松解析。inspectp
0赞 engineersmnky 6/22/2023
你为什么要用你之前的答案重新发布这个作为参考,然后重新发布一个几乎相同的答案来回答你自己的问题?这又回到了这个问题?
0赞 Felipe Hoffa 6/22/2023
这是纯粹的 Python 解决方案(我知道,我也讨厌初始字符串)。也许有更好的方法可以在 Python 中解析它?我发帖以防有人知道。同时,Snowflake 标签中的问题解决了如何在 SQL UDF 中封装此代码的问题。

答:

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