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.
Second step is to define the json object.
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
Practice Problem 2: Write a Python program to convert Python object to JSON data
First step is to import the json package.
Second step:
Define the python dictionary which is to be converted to a json object.
Third step: Convert python dictionary to Json object
Convert the python dictionary to json object using json.dumps() function from above imported json package.
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.