JSON (and JSON)

Introduction

  • Very very similar (see this and this)
  • JSON stands for “javascript object notation” and YAML stands for “yet another markup language”
  • Used in similar applications as xml. Were born because XML was considered too verbose or rich for many more limited applications. Json is much better known at this point.

Example

"menu": {
  "id": "file",
  "value": "File",
  "popup": {
    "menuitem": [
      {"value": "New", "onclick": "CreateNewDoc()"},
      {"value": "Open", "onclick": "OpenDoc()"},
      {"value": "Close", "onclick": "CloseDoc()"}
    ]
  } 
}

The same text expressed as XML:

<menu id="file" value="File">
  <popup>
    <menuitem value="New" onclick="CreateNewDoc()" />
    <menuitem value="Open" onclick="OpenDoc()" />
    <menuitem value="Close" onclick="CloseDoc()" />
  </popup>
</menu>

Live coding

 1require 'json'
 2
 3puts "Convert from an array to Json:"
 4puts [1,2,3].to_json
 5
 6puts "\nConvert from a hash to json:"
 7puts ({ name: "Jonathan", birthday: "Dec 1, 1991" }.to_json)
 8
 9puts "\nConvert from an arbitrary class:"
10class Car
11  def initialize make, model
12    @make = make
13    @model = model
14  end
15
16  def to_json
17    {'make' => @make, 'model' => @model}.to_json
18  end
19end
20
21c = Car.new("Toyota", "Corlla")
22puts c.to_json
23
24puts "\nAnd the other way around"
25name_hash = '{"name": "Pito", "town": "Arlington"}'
26puts JSON.parse(name_hash)
27
28name_list_hash = '[{"name": "Pito", "town": "Arlington"}, 
29                   {"name": "Chris", "town": "Willemstad"}, 
30                   {"name": "Amin", "town": "Lafayette"}]'
31puts JSON.parse(name_list_hash)
32
33puts "\n*** How about converting from XML to JSON?"
34require 'xmlsimple'
35
36xml = <<EOS
37<?xml version="1.0" encoding="UTF-8"?>
38<student>
39  <name>
40    Pito Salas
41  </name>
42  <gender>
43    male
44  </gender>
45</student>
46EOS
47
48xml_clean = xml.gsub(/\s/, '')
49xml_hash =  XmlSimple.xml_in(xml_clean , { 'ForceArray' => false })
50xml_json = xml_hash.to_json
51
52puts "Input xml string:", xml_clean
53puts "\nConverted to a hash:", xml_hash
54puts "\nConverted to a json string:", xml_json
55