gpt4 book ai didi

ruby - 在尝试解析之前检查字符串是否是有效的 json?

转载 作者:IT老高 更新时间:2023-10-28 12:46:01 35 4
gpt4 key购买 nike

在 Ruby 中,有没有办法在尝试解析字符串之前检查它是否是有效的 json?

例如从其他一些 url 获取一些信息,有时它返回 json,有时它可能返回一个无效响应的垃圾。

我的代码:

def get_parsed_response(response)
parsed_response = JSON.parse(response)
end

最佳答案

您可以创建一个方法来进行检查:

def valid_json?(json)
JSON.parse(json)
true
rescue JSON::ParserError, TypeError => e
false
end

关于ruby - 在尝试解析之前检查字符串是否是有效的 json?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26232909/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com