Playing with JSON

Some neat tips and tricks for interacting with and parsing JSON responses from an API.

Using Net::HTTP

require 'net/http'
require 'json'

url      = 'http://jsonplaceholder.typicode.com/posts/1'
uri      = URI(url)
response = Net::HTTP.get(uri)
standard = JSON.parse(response)

So until now nothing special. But what if you want to refer to standard hash keys as symbols instead of strings. Well, you can easily convert the keys to symbols by adding symbolize_names param.

symbol = JSON.parse(response, symbolize_names: true)

Also you can parse JSON response and create an OpenStruct with it.

struct = JSON.parse(response, object_class: OpenStruct)

Both symbolized hash and openstruct object could be extended with new key <=> value pair.

symbol[:name] = 'kobaltz'
struct.name   = 'kobaltz'

The cool thing that if you want to convert the openstruct back to a hash you can do it with struct.marshal_dump command. The result hash will include the new key <=> value pair you have added to it when it was an openstruct object.

Using HTTParty

All of the above applies to httparty library.

require 'httparty'
require 'json'

url = 'http://jsonplaceholder.typicode.com/posts/1'
response = HTTParty.get(url)

standard = JSON.parse(response.to_json)
struct   = JSON.parse(response.to_json, object_class: OpenStruct)
symbol   = JSON.parse(response.to_json, symbolize_names: true)
struct.marshal_dump
Alexander M Almost 8 years ago