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.

Leave a Reply