English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

JSON Ruby

In questa sezione ti spiegheremo come codificare e decodificare oggetti JSON utilizzando il linguaggio Ruby.

Configurazione dell'ambiente

Prima di codificare o decodificare dati JSON con Ruby, dobbiamo prima installare il modulo Ruby JSON. Prima di installare il modulo, devi prima installare Ruby gem, che utilizziamo per installare il modulo JSON. Ma se stai utilizzando l'ultima versione di Ruby, potresti già avere installato il gem, quindi possiamo utilizzare il seguente comando per installare il modulo Ruby JSON:

$gem install json

Analisi JSON con Ruby

Di seguito è riportato il dati JSON, che deve essere memorizzato nel file input.json:

file input.json

{
  "President": "Alan Isaac",
  "CEO": "David Richardson",
  
  "India": [
    "Sachin Tendulkar",
    "Virender Sehwag",
    "Gautam Gambhir"
  ],
 
  "Sri Lanka": [
    "Lasith Malinga",
    "Angelo Mathews",
    "Kumar Sangakkara"
  ],
 
  "Inghilterra": [
    "Alastair Cook",
    "Jonathan Trott",
    "Kevin Pietersen"
  ]
}

Il seguente programma Ruby è utilizzato per analizzare il file JSON sopra menzionato;

Esempio online

#!/usr/bin/ruby
require 'rubygems'
require 'json'
require 'pp'
 
json = File.read('input.json')
obj = JSON.parse(json)
 
pp obj

以上示例执行结果为:

{"President"=>"Alan Isaac",
 "CEO"=>"David Richardson",
 "India"=>
  ["Sachin Tendulkar", "Virender Sehwag", "Gautam Gambhir"],
"Srilanka"=>
  ["Lasith Malinga ", "Angelo Mathews", "Kumar Sangakkara"],
 "England"=>
  ["Alastair Cook", "Jonathan Trott", "Kevin Pietersen"]
}