简体   繁体   中英

How to convert a REQUEST response to Ruby nested Hash/Array

I'm using HTTParty to do an external API call like so:

@result = HTTParty.get('some/url')

The result is a 3/4 layers nested JSON object with arrays (the result is not always the same though, some times there are more nested objects, some times more arrays, some times no arrays, etc but it always either nested objects nested objects with arrays):

  {
  "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"
    }
    ...
}

Now I need to iterate over key/values (including nested key/values) of the result but when I do:

@result.respond_to?(:each)

or

@result["nested"].respond_to?(:each)

I get a false . I've also tried:

@n_result = @result.to_json

and

@n_result = JSON.parse(@result)

But I get the false in both cases. Any ideas?

This response does not seem to be a valid JSON, surrounding { and } are missing. Didn't JSON.parse returned any exception? I've tried offline:

@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"
      }
      }
  }
}

And then:

@result_r = JSON.parse(@result)

returns:

 => {"something"=>"SALE", "nested"=>{"something"=>"M2", "nested"=>{"something"=>"DK"}}}

Of course duplicate keys has been skipped.

Let you try:

@result_r = JSON.parse("{%s}" % @result)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM