Working with JSON in Python

From CodingNix
Revision as of 20:08, 29 August 2020 by Jayprakash (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

JSON is the abbreviation for JavaScript Object Notation. It is a lightweight data-interchange which is very easy to read. JSON stores data in very structured way. Python has a built-in module called json. It allows us to do JSON operations in Python. Main json module has three methods which are the following:-

json module
Method Operation
json.load() Loads the JSON content or JSON file as Python dictionary
json.dump() Writes Python dictionary as JSON content in file
json.dumps() Converts Python dictionary into JSON content

Reading the data from JSON file

import json # Importing json module

# Opening the file as read mode
with open( "test.json", "r" ) as f:
    data = json.load( f ) # Loading the JSON content as Python dictionary into data variable

print( data )

Writing the data in JSON file

import json # Importing json module

data = {
    "1": "Value1",
    "2": "Value2",
    "3": "Value3",

# Opening the file as write mode
with open( "data.json", "w" ) as f:
    json.dump( data, f ) # Writing data in file