How to get a particular field from JSON in Ruby

Tags: ruby jq

I need to implement a simple shell utility in Ruby which parses JSON from a file and return a particular field from it.

JSON examples to be parsed:

{"status": "fail", "messages": ["Out of capacity"]}

{"status": "success", "messages": [], "result": {"node": {"ip": "", "description": "", "id": 974, "name": "VM#3"}}}

Idea is to create a CLI utility with two parameters: JSON file to read and field from JSON to extract:

./get_json_field.rb ~/tmp.XXXXXX 'result.node.ip'
./get_json_field.rb ~/tmp.XXXXXX 'messages.0'

I'm struggling how to map 2nd parameter to parsed JSON data structure in Ruby. I can write an iterator for sure, splitting string to an array using dot as separator an go through it item by item but this doesn't look like elegant solution.

Any suggestions for more elegant way?


Take a look at jq it might already do what you are looking for.

jq .messages[0]
jq .node.message.ip


By : akuhn

This video can help you solving your question :)
By: admin