๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ python_json.asp
Python JSON
If you have a Python object, you can convert it into a JSON string by using the json.dumps() method.
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ library โ€บ json.html
json โ€” JSON encoder and decoder
February 23, 2026 - Extensible JSON encoder for Python data structures. Supports the following objects and types by default: Changed in version 3.4: Added support for int- and float-derived Enum classes. To extend this to recognize other objects, subclass and implement a default() method with another method that returns a serializable object for o if possible, otherwise it should call the superclass implementation (to raise TypeError).
Discussions

How to convert following string to JSON in python - Stack Overflow
How can i convert the below string to JSON using python? str1 = "{'a':'1', 'b':'2'}" More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - How to dump a dict to a JSON file? - Stack Overflow
I have a dict like this: sample = {'ObjectInterpolator': 1629, 'PointInterpolator': 1675, 'RectangleInterpolator': 2042} I can't figure out how to dump the dict to a JSON file as showed below: { ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Convert string to JSON in Python? - Stack Overflow
I'm trying to convert a string, generated from an http request with urllib3. Traceback (most recent call last): File " ", line 1, in data = json.load(data) ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Really struggling with parsing json and dictionaries
I have a feeling you're overthinking this. When you access a value using jq, you look through each level and determine which element you need from the next level. Sometimes, the item is an array, so you access it via its index; sometimes, it's an object, so you access it via its dictionary. Really it's exactly the same with Python, except you would be more explicit with the lookups. In this case, assuming you do only have one Vpc as shown in that JSON, you don't need any loops at all; you can just access it directly: cidr_block = vpc['Vpcs'][0]['CidrBlock'] The outer data structure is a dict, so access it via keys; its Vpc key contains a list, so access that via index; the only item in the list is a dict, so access it via the key you want. The reason why your loop gets the cidr and then fails is because it looks through every key in the outer dictionary; the first one is Vpc, so it works, but the second one is ResponseMetadata whose value is a dict, not a list, so you get the error as you're trying to index it like a list. And no, you don't need to dump it back to JSON; I'm not sure why you think you need to. JSON is a string format, which you can use to send data to and from an API, but you would only ever interact with that data in Python format. More on reddit.com
๐ŸŒ r/learnpython
16
3
September 30, 2022
๐ŸŒ
YouTube
youtube.com โ€บ watch
Learn how to convert records in a text file to JSON in python | Tutorial - YouTube
In this video you will learn how to convert records in a text file to JSON in python.#python #JSON #Pycharm #Tutorial #Coding #Learning
Published ย  July 8, 2020
๐ŸŒ
Real Python
realpython.com โ€บ python-json
Working With JSON Data in Python โ€“ Real Python
August 20, 2025 - Learn how to work with JSON data in Python using the json module. Convert, read, write, and validate JSON files and handle JSON data for APIs and storage.
๐ŸŒ
YouTube
youtube.com โ€บ shorts โ€บ 85SkkI4O93U
Convert to JSON Ready โ€“ #93 Python Dataclasses Tip
Enjoy the videos and music you love, upload original content, and share it all with friends, family, and the world on YouTube.
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ gloss_python_convert_into_JSON.asp
Python Convert From Python to JSON
If you have a Python object, you can convert it into a JSON string by using the json.dumps() method.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-json
Python JSON - GeeksforGeeks
December 23, 2025 - Python JSON (JavaScript Object Notation) is a data format for storing and transferring data, supported via the built-in json module for parsing, serializing and deserializing. This below diagram shows JSON flows from server to client as a string via json.dumps(), then parsed back to a dictionary with json.loads() for data access.
Find elsewhere
๐ŸŒ
DataCamp
datacamp.com โ€บ tutorial โ€บ json-data-python
Python JSON Data: A Guide With Examples | DataCamp
December 3, 2024 - JSON provides a simple and easy-to-read format for storing and retrieving configuration data. This can include settings for the application, such as the layout of a user interface or user preferences. IoT (Internet of Things). IoT devices often generate large amounts of data, which can be stored and transmitted between sensors and other devices more efficiently using JSON. python_obj = { "name": "John Doe", "age": 30, "email": "john.doe@example.com", "is_employee": True, "hobbies": [ "reading", "playing soccer", "traveling" ], "address": { "street": "123 Main Street", "city": "New York", "state": "NY", "zip": "10001" } } print(python_obj)
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ how-to-use-the-json-module-in-python
How to Use the JSON Module in Python โ€“ A Beginner's Guide
June 5, 2023 - This process involves serializing the JSON data and saving it to a file, which you can subsequently read and use as needed. The json.dump() function in Python allows you to store JSON data directly into a file.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ serializing-json-data-in-python
Serializing JSON data in Python - GeeksforGeeks
July 23, 2025 - json.dump() method can be used for writing to JSON file. Write data to a file-like object in json format. ... Converting python object and writing into json file.
๐ŸŒ
Zyte
zyte.com โ€บ home โ€บ blog โ€บ json parsing with python [practical guide]
JSON Parsing with Python [Practical Guide]
July 6, 2023 - Learn how to parse flat and nested JSON data with Python. This guide covers libraries, methods, and advanced json parsers like JMESPath and ChompJS.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ json-dump-in-python
json.dump() in Python - GeeksforGeeks
January 13, 2026 - The json.dump() function in Python is used to convert (serialize) a Python object into JSON format and write it directly to a file.
๐ŸŒ
JSON Formatter
jsonformatter.org โ€บ json-to-python
Best JSON to Python Converter
JSON to Python Online with https and easiest way to convert JSON to Python. Save online and Share.
๐ŸŒ
Code Institute
codeinstitute.net โ€บ blog โ€บ python โ€บ working with json in python: a beginnerโ€™s guide
Working with JSON in Python: A Beginner's Guide - Code Institute Global
February 6, 2024 - Here, the `json.load()` function reads the content of the โ€˜person.jsonโ€™ file and returns a Python object representing the JSON data. In this case, it will be a dictionary (`loaded_person`). You can then manipulate or display the loaded data as needed. When working with JSON data, readability is crucial. The `json` module provides options for formatting the output to make it more human-readable.
๐ŸŒ
Bobdc
bobdc.com โ€บ blog โ€บ pythonjson
Parsing JSON with Python
December 15, 2024 - The duration between each of these occasions is long enough that Iโ€™ve had to relearn some basics each time, so a year or two ago I made a sample JSON file that demonstrates a few data structures and features, and then I wrote a Python demo script that parses them.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ really struggling with parsing json and dictionaries
r/learnpython on Reddit: Really struggling with parsing json and dictionaries
September 30, 2022 -

So I do cloud devops and have managed to create a lot of automations using BASH. For example, using AWS cli tools with the default output format of json, I have written many scripts using the AWS cli where I pipe the output to jq and get the results I am looking for. Combined with tools like jqplay, I have accomplished a lot. But there is a limit to BASH's usefulness when you are doing more complex operations. For that reason I have tried to lean in and do more stuff in python. I have gotten pretty good at modifying existing code and have written some pretty useful smaller python scripts.

But several times over the last few months, I keep trying and failing to really comprehend pythons handling of json. Such that I have given up and gone back to bash to complete a project.

So I am asking for help with two things from r/learnpython.

  1. Solving the particular problem I am having right now.

  2. Finally understanding how to parse any json with python.

ONE - - - - - - My current problem.

So using the code below, I have learned how to just get my data using boto3, convert it to json using json.dumps() and pretty print the json. (By the way, I need to use the standard json library here)

import boto3, json
from sys import argv

account = argv[1]

##THE FUNCTION BELOW WORKS FINE AND IS NOT REALLY RELEVANT TO MY QUESTION
def get_app_vpc_name(account): 
    if 'sbx' in account:
        return 'sbx-app-' + account
    elif 'dev' in account:
        return 'dev-app-' + account
    elif 'tst' in account:
        return 'tst-app-' + account
    elif 'prd' in account:
        return 'prd-app-' + account

## SETUP boto3 FOR AWS API 
boto3.setup_default_session(profile_name=account)
ec2 = boto3.client('ec2')

## GET A PARTICULAR VPC OUTPUT
def get_app_vpc_cidr_block(account):
    app_vpc_cidr_blk_name = '-'.join([account, 'app-vpc-cidr-block'])
    vpc = ec2.describe_vpcs(
    Filters=[
        {
            'Name': 'tag:Name',
            'Values': [
                get_app_vpc_name(account)
            ]
        }
    ]
    )
## CONVERT PYTHON DICTIONARY TO JSON USING json.dumps
    vpc_json = json.dumps(vpc, indent=6)

## PRETTY PRINT THE JSON
    print(vpc_json)

---- output FROM ABOVE CODE

{
      "Vpcs": [
            {
                  "CidrBlock": "10.215.188.0/22",
                  "DhcpOptionsId": "dopt-a370e999",
                  "State": "available",
                  "VpcId": "vpc-046b1f660f8337999",
                  "OwnerId": "999092819999",
                  "InstanceTenancy": "default",
                  "CidrBlockAssociationSet": [
                        {
                              "AssociationId": "vpc-cidr-assoc-027d7fe136117b999",
                              "CidrBlock": "10.215.188.0/22",
                              "CidrBlockState": {
                                    "State": "associated"
                              }
                        }
                  ],
                  "IsDefault": false,
                  "Tags": [
                        {
                              "Key": "network_tier",
                              "Value": "app"
                        },
                        {
                              "Key": "network_name",
                              "Value": "llh-devapp"
                        },
                        {
                              "Key": "ingress_support",
                              "Value": "false"
                        },
                        {
                              "Key": "usage",
                              "Value": "central-network"
                        },
                        {
                              "Key": "network_environment",
                              "Value": "dev"
                        },
                        {
                              "Key": "Name",
                              "Value": "dev-app-llh-devapp"
                        },
                        {
                              "Key": "account_name",
                              "Value": "N/A"
                        }
                  ]
            }
      ],
      "ResponseMetadata": {
            "RequestId": "9619218c-be04-4e36-bc4c-e8c8411a7999",
            "HTTPStatusCode": 200,
            "HTTPHeaders": {
                  "x-amzn-requestid": "9619218c-be04-4e36-bc4c-e8c8411a7999",
                  "cache-control": "no-cache, no-store",
                  "strict-transport-security": "max-age=31536000; includeSubDomains",
                  "content-type": "text/xml;charset=UTF-8",
                  "content-length": "1966",
                  "date": "Fri, 30 Sep 2022 19:40:09 GMT",
                  "server": "AmazonEC2"
            },
            "RetryAttempts": 0
      }
}

So I have made a lot of progress, but where I have struggled for weeks is parsing the json (or even the dictionary before I convert it to json) to get the exact data I need. Over and over and over, I keep running into type and other errors, but I have not succeeded in just parsing and get just the data I need. from the json/dictionary.

In this particular case, all I want is to get the CidrBlock from the data. I have had partial success by working with the code below, appended to the above script. (I will just show the function with the extra code)

def get_app_vpc_cidr_block(account):
    app_vpc_cidr_blk_name = '-'.join([account, 'app-vpc-cidr-block'])
    vpc = ec2.describe_vpcs(
    Filters=[
        {
            'Name': 'tag:Name',
            'Values': [
                get_app_vpc_name(account)
            ]
        }
    ]
    )
    vpc_json = json.dumps(vpc, indent=6)
    print(vpc_json)
    ## EXTRA CODE. USING DICTIONARY ITEMS. JSON CODE ABOVE IS IRELEVANT
    for key, value in vpc.items():
        results = value
        print(results[0]['CidrBlock'])

I would like to add that I have tried a LOT of differnet things to simply retrieve the CidrBlock data. Depending on whether or not I dumped it to json, I have gotten so many errors. (Often type errors, but no real success.

Here is what the code above returns after the json print. (NOTE that it does return the CidrBlock before the error).

10.215.188.0/22
Traceback (most recent call last):
  File "./caller.py", line 6, in <module>
     get_app_vpc_cidr_block(aws_acct)
  File "/var/lib/jenkins/testscripts/getAppVpcCidrBlock.py", line 35, in get_app_vpc_cidr_block
print(results[0]['CidrBlock'])
KeyError: 0

Regarding this problem in particular, my only question is this.

What is the correct pythonic way to retrieve the damned CidrBlock value from the above dictionary/json and assign the value to a variable?

2----MORE GENERAL JSON QUESTIONS

  • Do I even need to convert output like above from a dictionary to json? (After retrieving the data using boto3, it is of the dictionary type.)

  • Once you have an object (json or dictionary), what is the proper way to parse it and get particular data from it. In my case I will almost always want to retrieve certain values from the data and assign variables to those values.

  • To illustrate the above question, suppose I wanted to retrive the following values from the json and assign each value to a variable

    • CidrBLock

    • VpcId

    • AssociationId (from CidrBlockAssociationSet)

    • Name Value (from tags)

  • Is there a python tool similar to jqplay that I can use to play with json to find the right python to get the data I want?

Thanks and I appreciate any help y'all can give me on this.

Top answer
1 of 4
6
I have a feeling you're overthinking this. When you access a value using jq, you look through each level and determine which element you need from the next level. Sometimes, the item is an array, so you access it via its index; sometimes, it's an object, so you access it via its dictionary. Really it's exactly the same with Python, except you would be more explicit with the lookups. In this case, assuming you do only have one Vpc as shown in that JSON, you don't need any loops at all; you can just access it directly: cidr_block = vpc['Vpcs'][0]['CidrBlock'] The outer data structure is a dict, so access it via keys; its Vpc key contains a list, so access that via index; the only item in the list is a dict, so access it via the key you want. The reason why your loop gets the cidr and then fails is because it looks through every key in the outer dictionary; the first one is Vpc, so it works, but the second one is ResponseMetadata whose value is a dict, not a list, so you get the error as you're trying to index it like a list. And no, you don't need to dump it back to JSON; I'm not sure why you think you need to. JSON is a string format, which you can use to send data to and from an API, but you would only ever interact with that data in Python format.
2 of 4
2
quick demo: >>> import json >>> >>> data = {"A": {"x": 1, "y": 2}, "B": {"x" : 7, "y": 8, "z": 9}} >>> print(data, type(data)) {'A': {'x': 1, 'y': 2}, 'B': {'x': 7, 'y': 8, 'z': 9}} >>> >>> # turn a dict into a JSON string >>> s = json.dumps(data, indent=4) >>> print(s) { "A": { "x": 1, "y": 2 }, "B": { "x": 7, "y": 8, "z": 9 } } >>> >>> # turn a JSON string into a python dict >>> d = json.loads(s) >>> print(d, type(d)) {'A': {'x': 1, 'y': 2}, 'B': {'x': 7, 'y': 8, 'z': 9}} >>> >>> # access some data >>> print(d) {'A': {'x': 1, 'y': 2}, 'B': {'x': 7, 'y': 8, 'z': 9}} >>> print(d['A']) {'x': 1, 'y': 2} >>> print(d['A']['y']) 2 >>> print(d['B']['y']) 8 If you follow the basics here ^ then you should be able to do whatever you need to do... these are just nested (hierarchical) dicts and a notation (json) to express them as strings
๐ŸŒ
Medium
medium.com โ€บ data-science โ€บ working-with-json-data-in-python-45e25ff958ce
JSON in Python Tutorial | TDS Archive
August 11, 2021 - Writing to json files, reading from json files explained and illustrated with examples in python.