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

JSON Ruby

Dans cette section, nous vous expliquerons comment encoder et décoder des objets JSON en utilisant le langage Ruby.

Configuration de l'environnement

Avant de coder ou de décoder des données JSON avec Ruby, nous devons d'abord installer le module Ruby JSON. Avant d'installer ce module, vous devez d'abord installer Ruby gem, et nous utilisons Ruby gem pour installer le module JSON. Cependant, si vous utilisez la dernière version de Ruby, vous pourriez déjà avoir installé le gem, et nous pouvons utiliser la commande suivante pour installer le module Ruby JSON :

$gem install json

Analyse JSON avec Ruby

Voici les données JSON, stockées dans le fichier input.json :

fichier input.json

{
  "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"
  ]
}

Le programme Ruby suivant est utilisé pour analyser le fichier JSON ci-dessus;

Exemple en ligne

#!/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"]
}