Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search a JSON Response using Ruby

Tags:

I'm using a Ruby script to interface with an application API and the results being returned are in a JSON format. For example:

{
  "incidents": [
    {
      "number": 1,
      "status": "open",
      "key": "abc123"
    }
    {
      "number": 2,
      "status": "open",
      "key": "xyz098"
    }
    {
      "number": 3,
      "status": "closed",
      "key": "lmn456"
    }
  ]
}

I'm looking to search each block for a particular "key" value (yzx098 in this example) and return the associated "number" value.

Now, I'm very new to Ruby and I'm not sure if there's already a function to help accomplish this. However, a couple days of scouring the Googles and Ruby resource books hasn't yielded anything that works.

Any suggestions?

like image 253
Kristopher Avatar asked Mar 14 '14 20:03

Kristopher


People also ask

How do I get JSON data in Ruby on Rails?

One way to use rails to parse json in a scalable and effective manner is to create a class that parses the JSON response and manages the data from the json fields using the object. The problem with this approach is we need to maintain the class and have to be clear on which fields are included in the JSON.

What does JSON parse do in Ruby?

Once we have the file loaded, we can parse the JSON data using the JSON. parse method. This method will create a Ruby hash with the JSON keys. Once loaded, we can proceed to work with the data like an ordinary Ruby hash.


Video Answer


1 Answers

First of all, the JSON should be as below: (note the commas)

 {
  "incidents": [
    {
      "number": 1,
      "status": "open",
      "key": "abc123"
    },
    {
      "number": 2,
      "status": "open",
      "key": "xyz098"
    },
    {
      "number": 3,
      "status": "closed",
      "key": "lmn456"
    }
  ]
}

Strore the above json in a variable

s =  '{"incidents": [{"number": 1,"status": "open","key": "abc123"},{"number": 2,"status": "open","key": "xyz098"},{"number": 3,"status": "closed","key": "lmn456"}]}'

Parse the JSON

h = JSON.parse(s)

Find the required number using map

h["incidents"].map {|h1| h1['number'] if h1['key']=='xyz098'}.compact.first

Or you could also use find as below

 h["incidents"].find {|h1| h1['key']=='xyz098'}['number']

Or you could also use select as below

h["incidents"].select {|h1| h1['key']=='xyz098'}.first['number']
like image 96
Kirti Thorat Avatar answered Oct 15 '22 22:10

Kirti Thorat