On Github itechdom / class-json-intro
tl;dr: JSON strikes a balance between being human readable and machine readable.
JSON is commonly used by APIs to send data back and forth when you don't need/want to render a full web page.
JSON data structures are typically either an object (similar to a hash for the purposes of this discussion) or an array of objects or other values.
JSON objects follow some rules:
You also have a few types of values available in a JSON structure:
var person = '{"name":"Jennifer Johnson","street":"641 Pine St.","phone":true,"age":50,"pets":["cat","dog","fish"]}'
Let's look at some data in JSON and XML.
The json library is part of the standard library these days, so there is no need to require it in your Gemfile.
Requiring the json library gives you JSON.parse and JSON.generate. It also adds a .to_json method to most objects.
require 'json' my_hash = { :hello => "goodbye" } puts JSON.generate(my_hash) #=> "{\"hello\":\"goodbye\"}" puts {:hello => "goodbye" }.to_json #=> "{\"hello\":\"goodbye\"}"
require 'json' person = "{\"name\":\"Jennifer Johnson\",\"street\":\"641 Pine St.\",\"phone\":true,\"age\":50,\"pets\":[\"cat\",\"dog\",\"fish\"]}" puts JSON.parse(person) #=> {"name"=>"Jennifer Johnson", "street"=>"641 Pine St.", "phone"=>true, "age"=>50, "pets"=>["cat", "dog", "fish"]}
Alternative Libraries:
Most JavaScript runtimes come with a JSON library built-in.
JSONLint: checks the validity of JSON.
Along with building APIs, a common case for JSON is to dynamically load content into your page using AJAX.
The "X" in AJAX stands for XML, but it's common to use JSON these days.
In fact, requesting JSON from the server is so common that jQuery provides your with a helpful function:
// this is similar to $.get(), except the last parameter which is the data type $.getJSON('/tweets.json', function (data) { console.log(data); });