我正在使用HTTParty进行外部API调用,如下所示:
@result = HTTParty.get('some/url')
结果是一个带有数组的3/4层嵌套JSON对象(结果并不总是相同,有时候有更多嵌套对象,有时候有更多数组,有时没有数组等,但它总是嵌套对象嵌套对象与数组):
{
"something": "10100014",
"something": "025MH-V0625",
"something": null,
"something": null,
"something": "SALE",
"nested": {
"something": "DETACHED_HOUSE",
"something": null,
"something": "2014",
"something": 0,
"something": 138,
"something": 0,
"something": null,
"something": "A2010",
"something": "M2",
"nested": {
"something": "Tværagervej",
"something": "34A",
"something": "",
"something": null,
"something": "København S",
"something": "2300",
"something": "DK"
}
...
}
现在我需要迭代结果的键/值(包括嵌套键/值),但是当我这样做时:
@result.respond_to?(:each)
或
@result["nested"].respond_to?(:each)
我得到false
。我也试过了:
@n_result = @result.to_json
和
@n_result = JSON.parse(@result)
但在这两种情况下我都得到了false
。有什么想法吗?
答案 0 :(得分:0)
此响应似乎不是有效的JSON,而{
和}
缺失。 Didn&#t; t JSON.parse
是否有任何例外?我已经离线了:
@result = %Q{
{
"something": "10100014",
"something": "025MH-V0625",
"something": null,
"something": null,
"something": "SALE",
"nested": {
"something": "DETACHED_HOUSE",
"something": null,
"something": "2014",
"something": 0,
"something": 138,
"something": 0,
"something": null,
"something": "A2010",
"something": "M2",
"nested": {
"something": "Tværagervej",
"something": "34A",
"something": "",
"something": null,
"something": "København S",
"something": "2300",
"something": "DK"
}
}
}
}
然后:
@result_r = JSON.parse(@result)
返回:
=> {"something"=>"SALE", "nested"=>{"something"=>"M2", "nested"=>{"something"=>"DK"}}}
当然已经跳过重复键。
让你试试:
@result_r = JSON.parse("{%s}" % @result)