Create & Parse JSON in Ruby

Discussion in 'Ruby on Rails' started by pradeep, Sep 20, 2012.

  1. pradeep

    pradeep Team Leader

    Apr 4, 2005
    Likes Received:
    Trophy Points:
    Kolkata, India
    Home Page:
    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, either by cloning the Git repository or downloading a snapshot of the repository.

    As root issue the following commands:
     # rake install
     # rake install_pure
    Or, you can use Rubygems to install

     # gem install json
     # gem install json_pure

    Using The JSON Module

    To load the module you can write

     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:

     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.

     # 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.

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice