Tearzz
Tearzz

Reputation: 321

Extracting specific JSON data

I receive (similar to) the following JSON data:

    {"accountId"=>"some-private-really-long-account-id",
     "stats"=>
      {"score"=>
        {"globalScore"=>
          [{"key"=>"lifetimeScore", "value"=>"571",

          "key"=>"someOtherKeyHere", "value"=>"someValue"}]}

I am not quite sure how I would get the lifetime score. I've tried doing stuff like this:

puts data["globalScore"]["lifetimeScore"]["value"]

But that doesn't work. (data is of course the JSON data received).

Upvotes: 0

Views: 865

Answers (2)

Lemon Cat
Lemon Cat

Reputation: 1152

I believe the problem here is that data["globalScore"]["lifetimeScore"]["value"] doesn't reference a valid "path" within the JSON. Better formatting helps to clarify this:

  hash = {
    "accountId" => "some-private-really-long-account-id",
    "stats" => {
      "score" => {
        "globalScore" => [
          {
            "key"   => "lifetimeScore", 
            "value" => "571", 
            "key"   => "someOtherKeyHere", 
            "value" => "someValue"
          }
        ]
      }
    }
  }

This Ruby hash has some issues since a hash can't actually have multiple values for a given key, but that aside,

hash['stats']['score']['globalScore'][0]['value']

is a perfectly valid way to access the 'value' field.

My point is that the problem with the original question is not that hash#dig(...) should be used (as shown by @Phlip), it is that the "path" through the Hash data structure was actually invalid.

hash.dig("globalScore", "lifetimeScore", "value)

will fail just like the bracketed syntax in the original question.

Upvotes: 1

Phlip
Phlip

Reputation: 5343

Use JSON.parse(body) to convert your json to a hash. Then use hash.dig('stats', 'score', 'globalScore', 0, 'value') to run queries on that hash.

Upvotes: 1

Related Questions