Ruby Programming Tutorial - Lesson 40 - Javascript Object Notation JSON in Ruby

in ruby •  7 years ago  (edited)

json-logo.png

26106186415_407e7cc83a_c.jpg

JavaScript Object Notation (JSON)

JSON is a lightweight data-interchange format. It is easy for us humans to read and write. Plus, equally simple for machines to generate or parse. JSON is completely language agnostic, making it the ideal interchange format.

Built on two universally available structures:

  1. A collection of name/value pairs. Often referred to as an object, hash table, record, struct, keyed list, or associative array.
  2. An ordered list of values. More commonly called an array, vector, sequence or list.

JSON is similar to Hashes in Ruby, but it's not a ruby Hash, that is why we need to parse it into a ruby hash, in order to use it, in our ruby programs. The reason why it is not a ruby hash, is because it uses keys instead of symbols :) and it comes from a different world, the world of Javascript :)

1*OF0xEMkWBv-69zvmNs6RDQ.gif

Notice that where we have Symbols (:fullname => "bilal" or fullname: "bilal') and a corresponding values in hashes, in JSON there exist no symbols, but rather they are called keys "fullname" : "Bilal Haider", key is surrounded by double quotes .. so no symbols, no hashes :)

Because JSON is widely used in interchanging data, across applications, we need to learn to handle this Data Notation in ruby, that's why we need to learn to work with it :)

{
     "fullname" : "Bilal Haider"
     "age": 27
     "address": "Islamabad Pakistan"
}

Here is the qualities of JSON objects

  1. JSON objects are surrounded by curly braces {}.
  2. JSON objects are written in key/value pairs.
  3. Keys must be strings, and values must be a valid JSON data type (string, number, object, array, boolean or null).
  4. Keys and values are separated by a colon.
  5. Each key/value pair is separated by a comma.

Here is another example of a more complex Json Object

{
    "name":"John",
    "age":30,
    "cars": {
        "car1":"Ford",
        "car2":"BMW",
        "car3":"Fiat"
    }
 } 

Ruby provides us a module called JSON which has few methods, which we can use to handle JSON data objects, we call it parsing Json objects

Lets us see how we do that, by taking an example :)

The Task

Create a ruby program that reads Json data from file, and parse it into a ruby hash, so that each data item can be used in ruby programs

require 'json'

_data = File.read("data")
puts "Displaying Data as is: "
puts _data

_myhash = JSON.parse(_data)

puts "Displayed Hashed data: "
puts _myhash

## Once your data is parsed into a hash
## you can use it like so 

puts _myhash["name"]
puts _myhash["age"]
puts _myhash["cars"]

We have a file named data which has dummy data, which we want to parse into a ruby hash

It is possible to get JSON data from a website url or link, which is a method to share your application's data with the world, where other programmers can use your data in their applications.
Here is the result of our ruby program :)

Screenshot from 2018-03-27 18-12-26.png

By following same approach, we can also create JSON objects, and share our application's data, with the world..

which other people can parse into hashes and create awesome ruby programs for themselves or for to share with the world.

How to convert my hash into JSON and save that data in a text file ?

require 'json'

my_hash = {name: "bilal", age: "27", hobbies: {first: "programming", second: "ruby"}}
_mydata = JSON.generate(my_hash)

File.open("data2", "w") do |f|
    f.print _mydata
end

Notice that here, we have a data in the form of a hash, and we converted into a JSON object, which we then using Filing store in our file called data2

Screenshot from 2018-03-27 18-28-10.png

If you guys follow my articles on daily basis and want to contact me for something
Here is my discord Group, where we are working on an open source crypto currency project.

https://discord.gg/UhQCYeb

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  

Another cool thing.

glad you liked it :)

Thank you for your very important and helpful information

You are welcome :)

Wow.....nice topic...i hope this is not the last lesson

Why do you think, it can be the last lesson ? :p I have my target of writing 1000 ruby articles, and I am not doing this for money .. I am setting a Path for other people to follow if they want to become Pro ruby coders :)

Yea true talk.....i love that

Congratulations @bilal-haider! You have completed some achievement on Steemit and have been rewarded with new badge(s) :

Award for the number of upvotes

Click on any badge to view your own Board of Honor on SteemitBoard.

To support your work, I also upvoted your post!
For more information about SteemitBoard, click here

If you no longer want to receive notifications, reply to this comment with the word STOP

Upvote this notification to help all Steemit users. Learn why here!

A very nice post, i just got an idea on the JavaScript Object Notation.

I am glad you liked it :) JSON is widely used, when it comes to sharing data with other applications.