Posted over 5 years ago. Visible to the public. Linked content.

Playing with JSON

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

Using Net::HTTP

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

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

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

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

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

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

Copy
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

Owner of this card:

Avatar
Alexander M
Last edit:
over 5 years ago
by Alexander M
Posted by Alexander M to Ruby and RoR knowledge base
This website uses short-lived cookies to improve usability.
Accept or learn more