Read Json File in Python

JSON(JavaScript Object Notation) is a lightweight data-interchange format that easy for humans to read and write.It's common to transmit and receive data between a server and web application in JSON format. It is also easy for computers to parse and generate. JSON is based on the JavaScript programming language. It is a text format that is language independent and can be used in Python, Perl among other languages. It is primarily used to transmit data between a server and web applications. JSON is built on two structures:  

  • A collection of name/value pairs. This is realized as an object, record, dictionary, hash table, keyed list, or associative array.
  • An ordered list of values. This is realized as an array, vector, list, or sequence.

The syntax of JSON is considered as a subset of the syntax of JavaScript including the following:

  • Keys must be strings.
  • Name/Value pairs: Represents Data, name is followed by ‘:'(colon) and the Name/Value pairs separated by, (comma).
  • Curly braces: Holds objects.
  • Square brackets: Hold arrays with values separated by, (comma).

Json String

Particularly, we will use this string in the examples. It is just a regular multi-line Python string that follows the JSON format.

 data_JSON =  """
{
    "size": "Medium",
    "price": 15.67,
    "toppings": ["Mushrooms", "Extra Cheese", "Pepperoni", "Basil"],
    "client": {
        "name": "Jane Doe",
        "phone": "455-344-234",
        "email": "janedoe@email.com"
    }
}
"""

  • To define a multi-line string in Python, we use triple quotes.  
  • Then, we assign the string to the variable data_JSON.

Json String to python Dictionary

We will use the string with JSON format to create a Python dictionary that we can access, work with, and modify. To do this, we will use the loads() function of the json module, passing the string as the argument.

# Import the module
import json
# String with JSON format
data_JSON = """
{
"size": "Medium",
"price": 15.67,
"toppings": ["Mushrooms", "Extra Cheese", "Pepperoni", "Basil"],
"client": {
"name": "Jane Doe",
"phone": "455-344-234",
"email": "janedoe@email.com"
}
}
"""
# Convert JSON string to dictionary
data_dict = json.loads(data_JSON)
print(data_dict)
  • json.loads(data_JSON) creates a new dictionary with the key-value pairs of the JSON string and it returns this new dictionary.
  • Then, the dictionary returned is assigned to the variable data_dict.

Awesome! If we print this dictionary, we see this output:

{'size': 'Medium', 'price': 15.67, 'toppings': ['Mushrooms', 'Extra Cheese', 'Pepperoni', 'Basil'], 'client': {'phone': '455-344-234', 'email': 'janedoe@email.com', 'name': 'Jane Doe'}}

print(data_dict["size"])
print(data_dict["price"])
print(data_dict["toppings"])
print(data_dict["client"])

Medium
15.67
['Mushrooms', 'Extra Cheese', 'Pepperoni', 'Basil']
{'email': 'janedoe@email.com', 'name': 'Jane Doe', 'phone': '455-344-234'}

 

import json 

Following methods are available in the JSON module

  • dump() - encoded string writing on file
  • dumps() - encoding to json string
  • load() - Decode while JSON file read
  • loads() - Decode the JSON String

In Python, JSON exists as a string. For example:

p = '{"name": "Bob", "languages": ["Python", "Java"]}'

It's also common to store a JSON object in a file.

Import Json Module 

To work with JSON (string, or file containing JSON object), you can use Python's json module. You need to import the module before you can use it.

import json

# Python program to read json file
import json
person = '{"name": "Bob", "languages": ["English", "Fench"]}'
person_dict = json.loads(person)
# Output: {'name': 'Bob', 'languages': ['English', 'Fench']}
print( person_dict)
# Output: ['English', 'French']
print(person_dict['languages'])

Python Read Json File

All arguments have the same meaning in both methods.

The json.load() is used to read the JSON document from file and The json.loads() is used to convert the JSON String document into the Python dictionary.

Convert from Python to JSON
import json
# Data to be written
dictionary ={
"id": "04",
"name": "sunil",
"depatment": "HR"
}
# Serializing json
json_object = json.dumps(dictionary, indent = 2)
print(json_object)

 

No comments:

Post a Comment