【发布时间】:2017-11-14 04:23:12
【问题描述】:
我有一些 JSON 代码用于使 Ruby 应用程序正常工作。它检查了大多数 linter 和验证器(我还没有尝试过它不起作用的一种。)
但问题是,它的 Ruby 库不起作用。我继续尝试它,用不同的方式和尝试,但它就是无法正确加载。它给了我一个意外的令牌错误。我只是很困惑,因为它适用于我尝试过的其他验证器。是宝石坏了,还是我做错了什么?
编辑:正在使用的代码是 JSON.parse 方法,在来自 file.read 方法的 to_json 方法之后。内容是直接从文件中读取的。
内容:
{
"black":{ "id":10, "title":"Black Room",
"desc":"You're in a large, black room filled with cobwebs.",
"around":[20, 30], "items":[], "npcs":[] },
"grey":{ "id":20, "title":"Grey Room",
"desc":"You're in a fine, grey room filled with nothing all.",
"around":[10, 20], "items":[], "npcs":[] },
"white":{ "id":30, "title":"White Room",
"desc":"You're in a small, white room filled with sunlight.",
"around":[10, 30], "items":[], "npcs":[] },
"null":{ "id":0, "title":"Null Room",
"desc":"You shouldn't be in here... please leave.",
"around":[10, 20, 30], "items":[], "npcs":[] }
}
【问题讨论】:
-
“我做错了吗?”...我们不知道...我们需要查看一个您在使用时遇到问题的 JSON 示例以及您的代码重新使用不会产生正确的结果。
-
@SimpleLime 就是这样。它适用于许多其他领域。我已经在 linter、validators 和 JS 中尝试过。它唯一不起作用的地方是 Ruby gem。
-
“我做错了吗?”请留下代码示例。如果您的问题是“Ruby 是否解析有效的 JSON?”那么答案是肯定的。如果您希望有人告诉您为什么您的 Ruby 代码不起作用,请发布您的 RUBY 代码。
-
你写的那些行是红宝石哈希的候选者。通常将 json 字符串传递给
JSON.parse以将其转换为哈希对象。但是,您可以将此哈希转换为字符串 -you_hash.to_json,然后将结果传递给JSON.parse。因此你会看到不会有错误 -
@marmeladze 我使用了 to_json 函数。