Ruby - Parse array of json files

1.8k Views Asked by At

I have an array of json files.this is the sample of single json file,

{
  "job": [
    "admin",
    "developer"
  ],
  "name": "dave"

}

i need to get the "name" value if admin exist in "job". Need to do the same for other json files in the array.

Helps would be appreciated.

2

There are 2 best solutions below

2
On

I am assuming if hash["job"] is present its an Array.

require 'json'
str = '{ "job": [ "admin", "developer" ], "name": "dave"}'
hash = JSON::parse(str)
# => {"job"=>["admin", "developer"], "name"=>"dave"}
name = hash["name"] if hash["job"] && hash["job"].include?("admin")
# => "dave"
0
On

Read the json file to hash using File Handling.

1) You need to require JSON before JSON parse.

 require 'json'

If the above step returns false then probably you don't have json gem installed on your machine. Install JSON gem using the following command.

gem install json

2) Open JSON file for parsing : Create file handle to parse JSON file.

file = File.read('file-name-to-be-read.json')

The above command will open the file in the read mode.

3) Now parse the data from the file.

data_hash = JSON.parse(file)

The above command will parse the data from the file using file handle created with name 'file' and variable data_hash will have parsed hash from the file.

4) Now if we take the example mentioned in the question.

{
  "job": [
    "admin",
    "developer"
  ],
  "name": "dave"
}

require 'json'
file = File.read('file-name-to-be-read.json')
data_hash = JSON.parse(file)

The data_hash will contain {"job"=>["admin", "developer"], "name"=>"dave"}

Now the key "job" from the above hash consist of an array that includes ["admin","developer"]. You can use the following ternary command to find out the name if the job is "admin".

data_hash["job"].select{|x| x == 'admin'}.any? ? data_select["name"] : "not found"

any? checks for the job, if it is 'admin' then it will provide the name.