Welcome to CCP
Lets get started !
So, today we're gonna deep dive into what's called 'JSON',
Hey ! wait a minute, What on earth this "JSON" is ?
JSON means JavaScript Object Notation,
I know, those of you who have 1st time heard this thing must be wondering why we are using javascript in python ?
Actually, we are not, its just the case that the syntax of javascript to declare an object somewhat matches python's dictionaries, but we are python lovers right ? So lets get straight into it:
You can import this library/module like this:
import json
Hah ! its that simple !
You don't even need to "pip install" it, it is built-in, we just have to import it to play with it,
Have ever seen any file with extension ".json" ?
if not, we will be making it and using it, these are simple organised text files which are much easier to parse/extract information from it,
Lets suppose, you are having some information in a text file, and it would take you to extract it complexly using RegEx and all that stuff, to save your time, you will use json files and this json module is only applicable on them,
Let us take a file named "ccp.json", lets have a look at it that how it looks:
Did you notice any similarity in the above image ?
This is a list of dictionaries just like python,
We made a list of dictionaries so that we can store abouts of multiple people,
if you want, you can store only one person abouts in the json file, then also, it will be read by the json module,
Lets find out how to read this file:
And never forget to read the explanations written in the code, these are line-by-line explanations which you should read to get an in-depth knowledge of the topic !
So this was all about reading the json file,
Now, lets see how to write python dictionary or a list of dictionaries in a json file with json's dump(data, <file-object>) method:
Now, lets look at our "ccp.json" file for any changes:
Woohoo ! you wrote your first json file !
But, Doesn't it looks so simple ?
Lets fix it to make it catchy from human eye,
(it maybe readable for now but what if we we had big data, in this form, it will look horrible to read from human eye)
We will be passing 1 more argument to the json.dump() method, which is "indent",
This will make our file cool !
Now, lets look at our "coolified" json file:
Now, thats like it !
You can also pass a list of dictionaries as dump() method's first argument to write lots and lots of data into your file !
So, that was your small lesson on the module "json",
Meet you ! in the next, tutorial !
Till then, have fun coding !
It was a decent tutorial but i suggest you to keep posting your tutorials faster as i was waiting for a week to get them
ReplyDeleteElse everything was just fine !
Thanks for sticking with the site,
DeleteWe are try hard to make more tutorials in faster period of time