Flip Flip - 7 months ago 24
Ruby Question

How to handle large JSON data when exploring an API?

Often I find myself in the situation where I start exploring a new API and get
back large JSON objects. And everytime I struggle to find a way to display them properly indented, so that I can easily see the structure and identify the parts relevant to my task.

Right now I am exploring the Z-Wave API for Razberry (Home Automation). I get back a JSON holding all the devices connected to the Home Automation network. It looks like this:

enter image description here

And I don't understand why Rails breaks the lines in the way it can be seen here, and why it doesn't manage to indent the JSON data properly. The output on the screenshot is the result of this controller code:

request = Net::HTTP::Get.new(uri)
request.basic_auth 'admin', 'bla'

response = Net::HTTP.start(uri.hostname, uri.port) do |http|
http.request(request)
end

@devices = JSON.parse(response.body)
render json: @devices


It would be interesting to see how more experienced programmers handle JSON at this stage, when exploring the datastructure. How can I display the JSON in this
style?:



{"1":
{"instances":
{"0":{
"commandClasses":
{"32":
{"name":"Basic",
"data":
{"invalidateTime":1462455293,
"updateTime":1462365990,
"type":"empty",
"value":null,
"supported":
{"invalidateTime":1462455293,
"updateTime":1462365990,
"type":"bool",
"value":true},
"version":



Answer

You can use JSON.pretty_generate() method:

Example:

require 'json'
my_json = { :array => [1, 2, 3, { :sample => "hash"} ], :foo => "bar" }
puts JSON.pretty_generate(my_json)

Output:

{
  "array": [
    1,
    2,
    3,
    {
      "sample": "hash"
    }
  ],
  "foo": "bar"
}

Your code:

request = Net::HTTP::Get.new(uri)
request.basic_auth 'admin', 'bla'

response = Net::HTTP.start(uri.hostname, uri.port) do |http|
  http.request(request)
end

@devices = JSON.parse(response.body)
render json: JSON.pretty_generate(@devices)