StackStalk
  • Home
  • Java
    • Java Collection
    • Spring Boot Collection
  • Python
    • Python Collection
  • C++
    • C++ Collection
    • Progamming Problems
    • Algorithms
    • Data Structures
    • Design Patterns
  • General
    • Tips and Tricks

Saturday, May 1, 2021

Python JSON

 May 01, 2021     Python     No comments   

JavaScript Object Notation (JSON) is a standard text-based format for representing structured data. In this article, we will look at examples to work with JSON in Python.
  1. Example - Read JSON from file as dictionary
  2. Example - Read JSON Array from file as list
  3. Example - Read JSON from input string as dictionary
  4. Example - Convert Python dictionary to JSON
  5. Example - Write JSON to file
  6. Example - Convert YAML to JSON
  7. Example - Convert JSON to YAML
  8. Example - Convert XML to JSON
  9. Example - Convert JSON to XML
Yaml and XML examples below need the Python Yaml and xmltodict modules to be installed.
pip3 install yaml
pip3 install xmltodict

Sample Input files

Input sample JSON and YAML files used in the examples.
{
    "id": "1",
    "title": "Black Panther",
    "year": "2018",
    "genres": [
        "Action",
        "Adventure",
        "Sci-Fi"
    ],
    "contentRating": "15",
    "duration": "PT134M",
    "releaseDate": "2018-02-14",
    "averageRating": 0,
    "originalTitle": "",
    "actors": [
        "Chadwick Boseman",
        "Michael B. Jordan",
        "Lupita Nyong'o"
    ],
    "imdbRating": 7.0
}
[
    {
        "id": "1",
        "title": "Black Panther",
        "year": "2018",
        "genres": [
            "Action",
            "Adventure",
            "Sci-Fi"
        ],
        "contentRating": "15",
        "duration": "PT134M",
        "releaseDate": "2018-02-14",
        "averageRating": 0,
        "originalTitle": "",
        "actors": [
            "Chadwick Boseman",
            "Michael B. Jordan",
            "Lupita Nyong'o"
        ],
        "imdbRating": 7.0
    },
    {
        "id": "2",
        "title": "Grottmannen Dug",
        "year": "2018",
        "genres": [
            "Animation",
            "Adventure",
            "Comedy"
        ],
        "contentRating": "PG",
        "duration": "PT89M",
        "releaseDate": "2018-03-23",
        "averageRating": 0,
        "originalTitle": "Early Man",
        "actors": [
            "Tom Hiddleston",
            "Eddie Redmayne",
            "Maisie Williams"
        ],
        "imdbRating": 6.3
    }
]
---
- actors:
  - Chadwick Boseman
  - Michael B. Jordan
  - Lupita Nyong'o
  averageRating: 0
  contentRating: '15'
  duration: PT134M
  genres:
  - Action
  - Adventure
  - Sci-Fi
  id: '1'
  imdbRating: 7.0
  originalTitle: ''
  releaseDate: '2018-02-14'
  title: Black Panther
  year: '2018'
- actors:
  - Tom Hiddleston
  - Eddie Redmayne
  - Maisie Williams
  averageRating: 0
  contentRating: PG
  duration: PT89M
  genres:
  - Animation
  - Adventure
  - Comedy
  id: '2'
  imdbRating: 6.3
  originalTitle: Early Man
  releaseDate: '2018-03-23'
  title: Grottmannen Dug
  year: '2018'
<?xml version="1.0" encoding="UTF-8"?>
<movies>
    <movie>
        <id>1</id>
        <title>Black Panther</title>
        <year>2018</year>
        <genres>Action</genres>
        <genres>Adventure</genres>
        <genres>Sci-Fi</genres>
        <contentRating>15</contentRating>
        <duration>PT134M</duration>
        <releaseDate>2018-02-14</releaseDate>
        <averageRating>0</averageRating>
        <originalTitle />
        <actors>Chadwick Boseman</actors>
        <actors>Michael B. Jordan</actors>
        <actors>Lupita Nyong'o</actors>
        <imdbRating>7.0</imdbRating>
    </movie>
</movies>

Example - Read JSON from file as dictionary

import json

# Read JSON from file as dictionary
def read_json_from_file():

    # Read JSON from file
    try:
        f = open("sample.json", "r")
        movie = json.load(f)
        print(movie)

        print(type(movie)) # movie is of type dict

        # Get title from dict
        print("Title is  : " + movie["title"])

        # Get list of genres
        print(type(movie["genres"])) # data["genres"] is list
        for genre in movie["genres"]:
            print(genre)

    except Exception as e:
        print("Error: " + str(e))
    finally:
        f.close()

def main():
    read_json_from_file()
    
main()

Example - Read JSON Array from file as dictionary

import json

# Read JSON Array from file as List
def read_json_array_from_file():

    # Read JSON from file
    try:
        f = open("sample_array.json", "r")
        movie_list = json.load(f)
        print(movie_list)

        print(type(movie_list)) # movie_list is of type list

        # Iterate over the list
        for movie in movie_list:
            print(movie["title"])

    except Exception as e:
        print("Error: " + str(e))
    finally:
        f.close()

def main():
    read_json_array_from_file()
    
main()

Example - Read JSON from input string as dictionary

import json

# Read JSON from input string as dictionary
def read_json_from_str():
    json_input =  """
    {
        "id": "2",
        "title": "Grottmannen Dug",
        "year": "2018",
        "genres": [
            "Animation",
            "Adventure",
            "Comedy"
        ],
        "contentRating": "PG",
        "duration": "PT89M",
        "releaseDate": "2018-03-23",
        "averageRating": 0,
        "originalTitle": "Early Man",
        "actors": [
            "Tom Hiddleston",
            "Eddie Redmayne",
            "Maisie Williams"
        ],
        "imdbRating": 6.3
    }
    """

    try:
        movie = json.loads(json_input)
        print(movie)

        print(type(movie)) # movie is of type dict

        # Get title from dict
        print("Title is  : " + movie["title"])

        # Get list of genres
        print(type(movie["genres"])) # data["genres"] is list
        for genre in movie["genres"]:
            print(genre)

    except Exception as e:
        print("Error: " + str(e))
        
def main():
    read_json_from_str()
    
main()        

Example - Convert Python dictionary to JSON

import json

# Write Python objects to JSON
# Convert Python dict to JSON
def write_objects_to_json():
    movie = {
        "id": 4,
        "title": "Grottmannen Dug",
        "actors": ["Tom Hiddleston","Eddie Redmayne","Maisie Williams"],
        "imdbRating": 6.3,
        "before2022": True
    }

    print(type(movie))
    print(json.dumps(movie))

    # Pretty print JSON
    print(json.dumps(movie, indent=4))

    # Pretty print JSON and sort keys
    print(json.dumps(movie, indent=4, sort_keys=True))
        
def main():
    write_objects_to_json() 
    
main()    

Example - Write JSON to file

import json

# Write JSON to file
def write_objects_to_json_file():
    movie = {
        "id": 4,
        "title": "Grottmannen Dug",
        "actors": ["Tom Hiddleston","Eddie Redmayne","Maisie Williams"],
        "imdbRating": 6.3,
        "before2022": True
    }

    print(type(movie))

    try:
        f = open("output.json", "w")
        f.write(json.dumps(movie, indent=4, sort_keys=True))
    except Exception  as e:
        print("Error: " + str(e))
    finally:
        f.close()

def main():
    write_objects_to_json_file()
    
main()

Example - Convert YAML to JSON

import json
import yaml
from yaml import Loader

# Convert YAML to JSON
def convert_yaml_to_json():
    # Read YAML from file
    try:
        f = open("sample.yaml", "r")
        data = yaml.load(f, Loader=Loader)
        print(json.dumps(data, indent=4))

    except Exception as e:
        print("Error: " + str(e))
    finally:
        f.close()

def main():
    convert_yaml_to_json() 
    
main()    

Example - Convert JSON to YAML

import json
import yaml
from yaml import Loader

# Convert JSON to YAML
def convert_json_to_yaml():
    # Read JSON from file
    try:
        f = open("sample_array.json", "r")
        movie_list = json.load(f)
        f = open("output.yaml", "w")
        yaml.dump(movie_list, f, explicit_start=True)

    except Exception as e:
        print("Error: " + str(e))
    finally:
        f.close()

    return None  


def main():
    convert_json_to_yaml() 
    
main()    

Example - Convert XML to JSON

import json
import xmltodict

# Convert XML to JSON
def convert_xml_to_json():

    # Read XML from file
    try:
        f = open("sample.xml", "r")
        movie = xmltodict.parse(f.read())
        print(type(movie))

        print(json.dumps(movie, indent=4))

    except Exception as e:
        print("Error: " + str(e))
    finally:
        f.close()

    return None


def main():
    convert_xml_to_json() 
    
main()        

Example - Convert JSON to XML

Note: This approach might not work well for complex JSON structure.
import json
import xmltodict

def convert_json_to_xml():

    json_input = """
{
    "movies":  [
      {
          "id": "1",
          "title": "Black Panther",
          "year": "2018",
          "genres": [
            "Action",
            "Adventure",
            "Sci-Fi"
          ],
          "contentRating": "15",
          "duration": "PT134M",
          "actors": [
            "Chadwick Boseman",
            "Michael B. Jordan"
          ],
          "imdbRating": 7.0
       }    
    ]
}
"""

    # Read JSON from input string
    try:
        movie = json.loads(json_input)
        print(type(movie))
        print(xmltodict.unparse(movie, full_document=False, pretty=True))

    except Exception as e:
        print("Error: " + str(e))

    return None


def main():
    convert_json_to_xml() 
    
main()
  • Share This:  
Newer Post Older Post Home

0 comments:

Post a Comment

Follow @StackStalk
Get new posts by email:
Powered by follow.it

Popular Posts

  • Avro Producer and Consumer with Python using Confluent Kafka
    In this article, we will understand Avro a popular data serialization format in streaming data applications and develop a simple Avro Produc...
  • Monitor Spring Boot App with Micrometer and Prometheus
    Modern distributed applications typically have multiple microservices working together. Ability to monitor and manage aspects like health, m...
  • Server-Sent Events with Spring WebFlux
    In this article we will review the concepts of server-sent events and work on an example using WebFlux. Before getting into this article it ...
  • Implement caching in a Spring Boot microservice using Redis
    In this article we will explore how to use Redis as a data cache for a Spring Boot microservice using PostgreSQL as the database. Idea is to...
  • Python FastAPI microservice with Okta and OPA
    Authentication (AuthN) and Authorization (AuthZ) is a common challenge when developing microservices. In this article, we will explore how t...
  • Spring Boot with Okta and OPA
    Authentication (AuthN) and Authorization (AuthZ) is a common challenge when developing microservices. In this article, we will explore how t...
  • Getting started with Kafka in Python
    This article will provide an overview of Kafka and how to get started with Kafka in Python with a simple example. What is Kafka? ...
  • Getting started in GraphQL with Spring Boot
    In this article we will explore basic concepts on GraphQL and look at how to develop a microservice in Spring Boot with GraphQL support. ...

Copyright © StackStalk