Working with JSON Data in Python

File handling | NumPy | Python Methods and Functions

# Show Python program
# use json package

 

import json

 
# {key: value mapping}

a = { " name " : "John" ,

"age" : 31 ,

"Salary" : 25000 }

  
# convert to JSON using the dumps () function

b = json.dumps (a)

 
# print output

print (b)

Output:

 {"age": 31, " Salary ": 25000," name ":" John "} 

As you can see, JSON supports primitive types such as strings and numbers, as well as nested lists, tuples, and objects.

# Python program showing that
# json supports various primitives
# types

 

import json

 
# convert list to array

print (json.dumps ([ `Welcome` , "to" , " Python.Engineering " ]))

  
# convert tuple to array

print (json.dumps (( "Welcome" , "to" , "GeeksforGeeks" )))

 
# convert string to string

print (json.dumps ( "Hi" ))

 
# int convert to number

print (json. dumps ( 123 ))

 
# convert number to floating point

print (json.dumps ( 23.572 ))

 
# Boolean conversion to appropriate values ​​

print (json.dumps ( True ))

print (json.dumps ( False ))

 
# No value to zero

print (json.dumps ( None ))

Exit :

 ["Welcome", "to", "GeeksforGeeks"] ["Welcome", "to", "GeeksforGeeks"] "Hi" 123 23.572 true false null 

JSON serialization:
The process of encoding JSON is commonly referred to as serialization . This term refers to the conversion of data into a series of bytes (hence sequential) for storage or transmission over a network. To process the stream of data in a file, the Python JSON library uses the dump () function to convert Python objects to their corresponding JSON objects, making it easier to write data to files. See the following table below.

Python object JSON object
dict object
list, tuple array
str string
int, long, float numbers
Truetrue
False false
None null

Serialization example:
Let`s look at the above example Python object.

Using

var =

  "Subjects" : {

  "Maths" : 85 ,

"Physics" : 90

}

}

with open ( "Sample.json" , "w" ) as p:

json.dumps (var, p)

Here dumps () first takes two arguments: serializable a data object, and then the object to which it will be written (in byte format).

Deserializing JSON:
Deserializing is the opposite of serializing, that is, converting a JSON object to appropriate im Python objects. The load () method is used for this. If you have used Json data from another program or received it as a Json string format, then it can be easily deserialized using load () , which is usually used to load from a string, otherwise the root object is in the list or dict.

with open ( "Sample.json" , "r" ) as read_it:

data = json.load (read_it)

Deserialization example:

json _var = "" "

{

& quot; Country & quot ;: {

& quot; name & quot ;: & quot; INDIA & quot ;,

& quot; Knowledge of foreign languages ​​& quot ;: [

{

& quot; names & quot ;: [& quot; Hindi & quot ;, & quot; English & quot ;, & quot; Bengali & quot ;, & quot; Telugu & quot;]

}

]

}

}
"" "

var = json.loads (json_var)

Encoding and decoding:
Encoding is defined as converting text or values ​​into an encrypted form that can only be used by the desired user by decoding it. Here encoding and decoding is done for JSON format (object). Encoding is also known as serialization and decoding — deserialization. Python has a popular package for this operation. This package is known as Demjson . Follow these steps to install it.
For Windows

 pip install demjson 

For Ubuntu

 sudo apt-get update sudo apt-get install python-demjson 

Encoding : The encode () function is used to convert a python object to a JSON string representation. Syntax

 demjson.encode (self, obj, nest_level = 0) 

Code 1: Encoding using the demjson package

# store 3 item ratings

var = [{ "Math" : 50 , " physics " : 60 , "Chemistry" : 70 }]

print (demjson.encode (var))

Exit :

 [{"Chemistry": 70, "Math": 50, "physics": 60}] 

Decode : The decode decode () function is used to convert a JSON object to a Python format type. Syntax

 demjson.decode (self, obj) 

Code 2: Decode using demjson package

var = `{" a ": 0," b ": 1," c ": 2, "d": 3, "e": 4} `

text = demjson.decode (var)

Exit:

 {`a`: 0,` b`: 1, `c`: 2,` d`: 3, `e`: 4 } 

Code 3: Encoding using iterencode

# Another encoding method

json.JSONEncoder (). encode ({ "foo" : [ "bar" ]})

`{" foo ": [" bar "]}`

 
# Using iterencode (object) to encode this object.

for i in json .JSONEncoder (). Iterencode (bigobject):

mysocket.write (i)

Code 4: Encoding and decoding with using dumps () and loads()

# To encode and decode operations

import json

var = { ` age` : 31 , `height` = 6 }

x = json.dumps (var)

y = json.loads (var)

print (x)

print (y)

  
# when executed from a file on disk

with open ( "any_file.json" , " r " ) as readit:

  x = json.load (readit )

print (x)

Real world example:
Let`s take a real example of JSON implementation in python. A good source for practice is
JSON_placeholder , it provides a great package of API requests that we will use in our example. Follow these simple steps to get started. Open the Python IDE or CLI and create a new script file, name it sample.py.

import requests

import json

 
# Now we need to request our JSON data via
# API package

res = requests.get ( " https://jsonplaceholder.typicode.com / todos " )

var = json.loads (res.text)

 
# To view the Json data, type var and hit enter

var

 
# Now our goal is to find a user who has
# Completed maximum my task !!
that is, we would calculate the true value
# User in the completed key.
# {

# & quot; userId & quot ;: 1,

# & quot; id & quot ;: 1,

# & quot; title & quot ;: & quot; Hey & quot ;,

# "completed": false, # we`ll assume

# this is for the user.

#}

 
# Please note that there are several users with
# unique identifier, and their tasks have matching
# Boolean values.

 

def find (todo):

check = todo [ "completed" ]

max_var = todo [ "userId" ] in users

return check and max_var

 
# To find values.

 

Value = list ( filter (find, todos))

 
# Write these values ​​to your disk

  

with open ( "sample.json" , "w" ) as data:

Value = list ( filter (keep, todos))

json.dump ( Value, data, indent = 2 )

To learn more, click here





Get Solution for free from DataCamp guru