![]() |
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 moduleThe 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:
Or, you can use Rubygems to install Code:
Using The JSON ModuleTo load the module you can write Code: Ruby
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:
To create a JSON string you need to keep the data inside a Array or Hash instance, follow the code sample below. Code: Ruby
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 03:23. |