「Ruby」JSON.parse()メソッドでJSON形式の文字列をRubyオブジェクトに変換するサンプル

環境構築
>gem install json
1.json形式の文字列
ファイル名 test.json

{
  "Username": "testuser001",
  "Addr": "home town is changfa",
  
  "Info": [
    "Baba",
    "Mainfo",
    "Meimei"
  ],
 
  "Pinpo": [
    "Pofan",
    "Nongcun",
    "Zhai"
  ],
 
  "ChangeInfo": [
    "Main",
    "Fuku",
    "Org"
  ]
}

2.parse()でjson形式の文字列をオブジェクトに変換
構文
parse(source, options = {}) -> object
source:json形式の文字列
サンプルコード

#!/usr/bin/ruby
# -*- coding: UTF-8 -*-
require 'rubygems'
require 'json'
require 'pp'
 
json = File.read('test.json')
cft = JSON.parse(json)
 
pp cft

3.実行結果

>ruby test.rb
{“Username"=>"testuser001",
“Addr"=>"home town is changfa",
“Info"=>[“Baba", “Mainfo", “Meimei"],
“Pinpo"=>[“Pofan", “Nongcun", “Zhai"],
“ChangeInfo"=>[“Main", “Fuku", “Org"]}

Ruby

Posted by arkgame