JSON stands for JavaScript Object Notation.

It looks like this: {"name": "value"}. It’s readable, right? It’s also readable to applications, regardless of which language it’s written in. Because of its readability and language-neutrality, JSON is widely used as a data exchange format.

Essentially, JSON is a string, containing a collection of double-quoted name and value pairs. The text format of JSON makes it easy for data to be passed from one system to the other (i.e., a server and a client, or two servers).

JSON is not directly manipulated, however. It needs to be parsed into a form that is easier to work with: a ruby hash. There is a library called JSON (duh) that gives us the following methods:


# alternative

Here’s an example. Note the data type of each object that’s either generated or parsed.

# in irb
> require 'JSON'
> some_hash = {:dog=>"baxter", :like=>"snuggle"}
> json_some_hash = JSON.generate(some_hash)
=> "{\"dog\":\"baxter\",\"like\":\"snuggle\"}"

> json_some_hash.class
 => String

> JSON.parse(json_some_hash)
 => {"dog"=>"baxter", "like"=>"snuggle"}

> JSON.parse(json_some_hash).class
 => Hash

> JSON.parse(json_some_hash, symbolize_names: true)
 => {:dog=>"baxter", :like=>"snuggle"}

Suppose that an app makes a GET request (i.e., a list of items) from an api. The response will be formatted in json, which needs to be parsed prior to manipulation.

# ../items_request_spec.rb
get '/api/v1/items'

items = JSON.parse(response.body)

Hence, JSON.parse is your friend when you’re working on request spec.