PYTHON JSON: ENCODE AND DCODE

PYTHON JSON: ENCODE AND DCODE

Date posted :16/05/2019

What is json:

JSON stands for JavaScript Object Notation. It may be a string or text format.

JSON is similar to python dictionary. Python has a inbuilt library for JSON.

syntax of JSON:

 {
     
      “key” : “value”,
      “key” : “value”,


    }

Encoding:

Converting python data into JSON is called encoding. dump() method used to encode the python data.

 import json

 x = {
   "name": "YYY",
  "age": 45,
   "married": True,
   "children": ("Alice","AAA"),
   "pets": ['Dog'],
   "cars": [
     {"model": "ROLS", "mpg": 15.1},
     {"model": "ZZZ", "mpg": 18.1}
   ]
 }
# sorting result in asscending order by keys:
 sorted_string = json.dumps(x, indent=4, sort_keys=True)
 print(sorted_string)

Output:

Decoding:

Decoding is done with the help of load() and loads() methods.

import json  # json library imported
# json data string
person_data = '{  "value":  { "name":  "YYY",  "sex":  "male",  "age":  28}}'
# Decoding or converting JSON format in dictionary using loads()
dict_obj = json.loads(person_data)
print(dict_obj)
# check type of dict_obj
print("Type of dict_obj", type(dict_obj))
# get human object details
print("VALUES",  dict_obj.get('value'))

Output:

Thanks for using pheonixsolutions.

You find this tutorial helpful? Share with your friends to keep it alive.

admin

Our team has expertise across software and web development, WordPress, e-commerce, mobile applications, UI/UX, cloud and infrastructure, DevOps, CI/CD, API integration, security, testing, automation, and technical support. The team also works with AI-based software solutions, LLMs, AI workflows, AI agents, and intelligent application development to help businesses automate processes and build smarter digital solutions. We focus on developing, deploying, maintaining, and optimising secure, scalable, and reliable technology solutions while helping businesses adopt modern technologies and drive digital transformation.

Leave a Comment

Scroll to Top