Go4Expert

Go4Expert (http://www.go4expert.com/)
-   Ruby on Rails (http://www.go4expert.com/articles/ruby/)
-   -   Create & Parse JSON in Ruby (http://www.go4expert.com/articles/create-parse-json-ruby-t29123/)

pradeep 20Sep2012 18:36

Create & Parse JSON in Ruby
 
JSON is the most popular format for exchanging data between different systems, primarily AJAX calls, web services, REST APIs, etc. Ruby combined with Rails is one of the best systems to quickly develop and deploy web applications makes use of JSON in all efficient ways.

The JSON module for Ruby is based on RFC 4627 specifications, in this article we'll see how to parse & convert to JSON structure using the JSON module for Ruby.

Installing the JSON module



The JSON module is available in 2 variants, one is the pure Ruby variant and the other a faster variant being the C extension variant. Usage of the extension variant is recommended, which if unavailable the
JSON module will automatically fallback on the pure Ruby variant.

Get the source from https://github.com/flori/json, either by cloning the Git repository or downloading a snapshot of the repository.

As root issue the following commands:
Code:

# rake install
 # rake install_pure


Or, you can use Rubygems to install

Code:

# gem install json
 # gem install json_pure


Using The JSON Module



To load the module you can write

Code: Ruby

require 'json'


This will try to load the extension variant first else the pure Ruby variant. To force load any specific variant you can write like this:

Code:

require 'json/ext'
 # or
 require 'json/pure'


To create a JSON string you need to keep the data inside a Array or Hash instance, follow the code sample below.

Code: Ruby

# to create a JSON string
 json = JSON.generate([11, 12, {"key"=>123}, false, true, nil])
 # outputs: "[11,12,{\"key\":123},false,true,null]"
 
 # to parse a JSON string
 data = JSON.parse(json)
 
 # JSON module always tries to create the leanest possible JSON string  stripping off unwanted whitespaces etc. to create a readable JSON  string, do this
 puts JSON.pretty_generate([11, 12, {"key"=>123}, false, true, nil])


That's all you need to know about working with JSON string in Ruby to get started with.


All times are GMT +5.5. The time now is 00:40.