JSON Python

To handle JSON Strings in Python

  • Python is a programming language that can also be used as server side scripting language for web
  • Python also provides two methods to handle JSON data exchange, within built-in package called "json"
  • So, you must import the "json" module to work with JSON data
  • Remember! All data exchange happen between client and sever are always in the form of string
  • turned_in_notMethods
    • json.loads()
    • json.dumps()

json.loads( )

Used to convert JSON String into python object of type dict (dictionary)

  • Similar to JSON.parse() at client side
  • Remember! You can also convert string like array (list in python) via this method into an array (list in python)
  • turned_in_notjson.loads
    import json
      
    jsonString = '{"name":"Rahul","love":"Music"}'
    #converting JSON String into an object
    obj=json.loads(jsonString)
    #To access an object syntax (objectName["keyName"])
    print("My name is",obj["name"])
    OUTPUT

    My name is Rahul

/* To access all key and values of an object inside Python */


Key=name, Value=Rahul
Key=love, Value=Music
import json

jsonString = '{"name":"Rahul","love":"Music"}';
#Converting JSON String into an object
obj=json.loads(jsonString)
#Accessing all key and values
for key in obj:
    print("Key="+key+",Value=",obj[key])


json.dumps( )

Used to convert an object into JSON String

  • Similar to JSON.stringify() at client side
  • turned_in_notjson.dumps
    import json
    
    # Converting python object type dict (dictionary)
    obj={"name":"Rahul","age":23,"love":"Music"}
    # Converting an object into JSON String
    myJSON = json.dumps(obj)
    print("My JSON String is ",myJSON)
    OUTPUT

    My JSON String is {"name":"Rahul", "age":23, "love":"Music"}


  • Remember! You can convert following python object types into JSON strings, and send it to the client
import json

print(json.dumps({"name":"Riya","age":23})) # type dict into Object
print(json.dumps(["A","B"]))  # type list into Array
print(json.dumps(("A","B")))  # type tuple into Array
print(json.dumps("hello"))    # type str into String
print(json.dumps(23))         # type int into Number
print(json.dumps(23.39))      # type float into Number
print(json.dumps(True))       # type True into true
print(json.dumps(False))      # type False into false
print(json.dumps(None))       # type None into null

/* Convertion Python Object */


{"dict_type": {"name": "Riya", "age": 23}, "list_type": ["A", "B"], "tuple_type": ["A", "B"], "str_type": "John", "int_type": 23, "float_type": 23.39, "True_type": true, "False_type": false, "None_type": null}

import json
objType = {
  "dict_type":{"name":"Riya","age":23},
  "list_type": ["A","B"],
  "tuple_type": ("A","B"),
  "str_type": "John",
  "int_type": 23,
  "float_type": 23.39,
  "True_type": True,
  "False_type": False,
  "None_type": None
}
print(json.dumps(objType))

/* More useful options */

import json
  
obj={"name":"Rahul","age":23,"love":"Music"}  # Python object type dict (dictionary)

# Converting an object into JSON String
myJSON = json.dumps(obj, sort_keys=True)  # sorted key format
print("Sorted JSON String is ",myJSON)

myJSON = json.dumps(obj, separators=(",","="))  # custom format
print("Custom JSON String is ",myJSON)

myJSON = json.dumps(obj, indent=2)  # readable format
print("Readable JSON String is ",myJSON)

# custom sorted readable format
myJSON = json.dumps(obj, sort_keys=True, separators=(",","="), indent=2)
print("Custom sorted readable JSON String is ",myJSON)

OUTPUT

Sorted JSON String is {"age": 23, "love": "Music", "name": "Rahul"}
Custom JSON String is {"name"="Rahul","age"=23,"love"="Music"}
Readable JSON String is {
  "name": "Rahul",
  "age": 23,
  "love": "Music"
}
Custom sorted readable JSON String is {
  "age"=23,
  "love"="Music",
  "name"="Rahul"
}


  • Remember! More like Python, there are other server scripting languages that also provides similar JSON handling methods

    Like in PHP,
    json_decode() used as json_parse() and  json_encode() used as json_stringify() at server side

  • Ajax
❮ Prev JSON PHP
TryOut Examples"Learn to Explore..!"

TryOut Editor

receipt