0

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).

5
  • Possible duplicate of parse json to object ruby Commented Mar 20, 2018 at 15:57
  • 2
    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. Commented Mar 20, 2018 at 15:59
  • Looks like the json data you posted is missing some "}", can you post the original one? Commented Mar 20, 2018 at 16:03
  • The original JSON data is wayyyyy too long. Commented Mar 20, 2018 at 16:06
  • @Phlip that worked thanks! :D Commented Mar 20, 2018 at 16:08

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.