module JSON
def self.is_json?(foo)
begin
return false unless foo.is_a?(String)
JSON.parse(foo).all?
rescue JSON::ParserError
false
end
end
end
puts 'it is json' if JSON.is_json?('{"name":"world"}')
json gem은 json과 json_pure 두개의 버전이 있다. gem install json을 실행할 경우 C 확장 버전이 설치가 된다. 따라서 C 컴파일러가 필요하다.
gem install json_pure를 실행하면 ruby로 작성된 josn 구현이 설치된다. 순수 ruby로 구현됐기 때문에, 플랫폼에 상관없이 사용할 수 있다. 대신 C 구현보다는 좀 더 느리다.
성능이 중요하지 않다면 json_pure를 사용하는 걸 권장한다. json을 사용할 경우 운영체제에 따라서 문제가 생길 수 있다. centos 5.4에서 json을 설치했더니, "uninitialized constant JSON (NameError)" 에러가 발생했다. 다른 ubuntu 리눅스에서는 잘 돌아간다. 버전은 1.8.7로 동일했다. 결국 ruby_pure를 설치해서 문제를 해결했다.
Contents
JSON
설치
JSON 데이터 생성
#!/usr/bin/ruby require 'rubygems' require 'json' myinfos = { "name"=>"yundream", "age"=>22, "hosts"=>["host1", "host2"] } puts myinfos.to_json{"age":22,"name":"yundream","hosts":["host1","host2"]}JSON parse
require 'json' require 'pp' str = '{ "CEO": "William Hummel", "CFO": "Carlos Work", "Human Resources": [ "Inez Rockwell", "Kay Mcginn", "Larry Conn", "Bessie Wolfe" ], "Research and Development": [ "Norman Reece", "Betty Prosser", "Jeffrey Barclay" ] }' empl = JSON.parse(str) pp empl{"Human Resources"=> ["Inez Rockwell", "Kay Mcginn", "Larry Conn", "Bessie Wolfe"], "CFO"=>"Carlos Work", "CEO"=>"William Hummel", "Research and Development"=> ["Norman Reece", "Betty Prosser", "Jeffrey Barclay"]}JSON 형식 검사
module JSON def self.is_json?(foo) begin return false unless foo.is_a?(String) JSON.parse(foo).all? rescue JSON::ParserError false end end end puts 'it is json' if JSON.is_json?('{"name":"world"}')json_pure
#!/usr/bin/ruby require 'rubygems' require 'json/pure' require 'pp' puts JSON.generate([1, 2, {"a"=>3.141}, false, true, nil, 4..10]) puts JSON 'test' => 23 a = JSON.parse('{"hello":"23"}') pp a# ./test.rb [1,2,{"a":3.141},false,true,null,"4..10"] {"test":23} {"hello"=>"23"}puts JSON.pretty_generate([1, 2, {"a"=>3.141}, false, true, nil, 4..10])[ 1, 2, { "a": 3.141 }, false, true, null, "4..10" ]json과 json/pure
히스토리
Recent Posts
Archive Posts
Tags