Working with JSON in Ruby


Here’s how to work with JSON in Ruby.

To parse JSON to Ruby objects

We can use JSON.parse() method as follow:

#JSON Parsing example
require "rubygems"
require "json"
string = '{"desc":{"someKey": "someValue", "anotherKey": "value" } ,"main_item": {"stats":{"a":8,"b":12,"c":10}}}'
parsed = JSON.parse(string) # returns a hash
p parsed["desc"]["someKey"]

To dumps/generate JSON from Ruby object

we can use JSON.generate() method as follow:

require 'json' 
my_hash = {:hello => "goodbye"} 
puts JSON.generate(my_hash) 
# ouput will be "{\"hello\":\"goodbye\"}" 

Our Awesome Tools



Working with JSON in Python


To work with JSON in Python, we need to import the json module:

 import json

To parse JSON to Python Object

We can use json.loads() method as follow:

import json

# some JSON:
x =  '{ "name":"", "age":30, "city":"New York"}'

# parse x:
y = json.loads(x)

# the result is a Python dictionary:

To dumps Python object to JSON

We can use json.dumps() method as follow:

import json

# a Python object (dict):
x = {
  "name": "",
  "age": 30,
  "city": "New York"

# convert into JSON:
y = json.dumps(x)

# the result is a JSON string:

Happy coding!