Python Daily Practice Challenge

Posted by

Hello all, today’s topic for daily challenge is working with JSON in Python. JSON  stands for JavaScript Object Notation and is a lightweight data-interchange format for storing and exchanging data.The JSON format is often used for serialising and transmitting structured data over a network connection. It is used primarily to transmit data between a server and web application, serving as an alternative to XML.

Practice Problem 1: Write a Python program to convert JSON data to Python object

Example of Json

'{
     "firstName": "John",
     "lastName": "Smith",
     "address": {
         "streetAddress": "21 2nd Street",
         "city": "New York",
         "state": "NY",
         "postalCode": 10021
     },
     "phoneNumbers": [
         "212 555-1234",
         "646 555-4567"
     ]
 }'

 

Python has a built-in package called json, which is used to work with JSON data.

First step is to import the json package.

Screenshot from 2020-05-12 16-24-44

Second step  is to define the json object.

Screenshot from 2020-05-12 16-21-33

Step 3: Convert json object to a python object

json.loads() function is used to convert  a json element to a python dictionary. json.loads() is a function of json library which takes input as a json element and gives output as a python dictionary.You can check if it a valid json by using jsonlint.com

Screenshot from 2020-05-12 16-26-17

 

Practice Problem 2: Write a Python program to convert Python object to JSON data

First step is to import the json package.

Screenshot from 2020-05-12 16-24-44

 

Second step:

Define the python dictionary which is to be converted to a json object.

Screenshot from 2020-05-12 16-27-38

 

Third step: Convert python dictionary to Json object

Convert the python dictionary to json object using json.dumps() function from above imported json package.

Screenshot from 2020-05-12 16-28-03

 

 

As we can see from the above code snippet, json.dumps() takes input a python dictionary and returns output as a python string which is a json object.

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s