1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Create & Parse JSON in Ruby

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

  1. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,646
    Likes Received:
    86
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    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 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:
     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:
     # 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