Very simple:

import json
data = json.loads('{"one" : "1", "two" : "2", "three" : "3"}')
print(data['two'])  # or `print data['two']` in Python 2
Answer from John Giotta on Stack Overflow
🌐
W3Schools
w3schools.com β€Ί python β€Ί python_json.asp
Python JSON
Python has a built-in package called json, which can be used to work with JSON data. ... If you have a JSON string, you can parse it by using the json.loads() method.
Discussions

Python Parse JSON array - Stack Overflow
I'm trying to put together a small python script that can parse out array's out of a large data set. I'm looking to pull a few key:values from each object so that I can play with them later on in the More on stackoverflow.com
🌐 stackoverflow.com
Using Python to Parse a JSON Object
I work as data engineer and we use marshmallow to deserialize JSON from application API's into Python objects. It's very nice because it also allows for data validation etc. We also serialize back into JSON for putting the objects into target applications. https://circleci.com/blog/object-validation-and-conversion-with-marshmallow/ More on reddit.com
🌐 r/PythonLearning
12
17
1 week ago
Handling JSON files with ease in Python
Looks good. Considered discussing dataclasses/pydantic with json? I found that these go well together More on reddit.com
🌐 r/Python
55
421
May 29, 2022
How to parse different part of json file (Newbie here)
I have created a python code that extracts jitter, latency, link, packet loss, timestamp from json file to csv file. However, inside this json file, there are multiple tests done (e.g. bronek 1, bronek 2, bronek 3, etc.) that under these testings have pair keys of jitter, latency, link, packet ... More on discuss.python.org
🌐 discuss.python.org
0
September 27, 2021
🌐
Python
docs.python.org β€Ί 3 β€Ί library β€Ί json.html
json β€” JSON encoder and decoder
3 weeks ago - If None (the default), it is equivalent to float(num_str). This can be used to parse JSON floats into custom datatypes, for example decimal.Decimal.
🌐
Bobdc
bobdc.com β€Ί blog β€Ί pythonjson
Parsing JSON with Python
December 15, 2024 - My sample demo data to parse is pretty close to the test input that I used when I wrote about JSON2RDF: { "mydata": { "color": "red", "amount": 3, "arrayTest": [ "north", "south", "east", "escaped \"test\" string", "west" ], "boolTest": true, "nullTest": null, "addressBookEntry": { "givenName": "Richard", "familyName": "Mutt", "address": { "street": "1 Main St", "city": "Springfield", "zip": "10045" } } } } ... #!/usr/bin/env python3 import json f = open('jsondemo.js') data = json.load(f) print(data["mydata"]["color"]) print(data["mydata"]["amount"]) # Pull something out of the middle of an ar
🌐
W3Schools
w3schools.com β€Ί python β€Ί gloss_python_json_parse.asp
Python JSON Parse
The result will be a Python dictionary. ... import json # some JSON: x = '{ "name":"John", "age":30, "city":"New York"}' # parse x: y = json.loads(x) # the result is a Python dictionary: print(y["age"]) Try it Yourself Β»
🌐
Zyte
zyte.com β€Ί home β€Ί blog β€Ί json parsing with python [practical guide]
JSON Parsing with Python [Practical Guide]
July 6, 2023 - To read JSON data, you can use the built-in json module (JSON Encoder and Decoder) in Python. The json module provides two methods, loads and load, that allow you to parse JSON strings and JSON files, respectively, to convert JSON into Python ...
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org β€Ί python β€Ί read-write-and-parse-json-using-python
Read, Write and Parse JSON using Python - GeeksforGeeks
August 28, 2025 - If you have JSON data stored in a .json file (for example, downloaded from an API or stored locally), Python's json module makes it easy to read and convert it into a Python dictionary using the json.load() function.
Top answer
1 of 2
46

In your for loop statement, Each item in json_array is a dictionary and the dictionary does not have a key store_details. So I modified the program a little bit

import json

input_file = open ('stores-small.json')
json_array = json.load(input_file)
store_list = []

for item in json_array:
    store_details = {"name":None, "city":None}
    store_details['name'] = item['name']
    store_details['city'] = item['city']
    store_list.append(store_details)

print(store_list)
2 of 2
0

If you arrived at this question simply looking for a way to read a json file into memory, then use the built-in json module.

with open(file_path, 'r') as f:
    data = json.load(f)

If you have a json string in memory that needs to be parsed, use json.loads() instead:

data = json.loads(my_json_string)

Either way, now data is converted into a Python data structure (list/dictionary) that may be (deeply) nested and you'll need Python methods to manipulate it.


If you arrived here looking for ways to get values under several keys as in the OP, then the question is about looping over a Python data structure. For a not-so-deeply-nested data structure, the most readable (and possibly the fastest) way is a list / dict comprehension. For example, for the requirement in the OP, a list comprehension does the job.

store_list = [{'name': item['name'], 'city': item['city']} for item in json_array]
# [{'name': 'Mall of America', 'city': 'Bloomington'}, {'name': 'Tempe Marketplace', 'city': 'Tempe'}]

Other types of common data manipulation:

  1. For a nested list where each sub-list is a list of items in the json_array.

    store_list = [[item['name'], item['city']] for item in json_array]
    # [['Mall of America', 'Bloomington'], ['Tempe Marketplace', 'Tempe']]
    
  2. For a dictionary of lists where each key-value pair is a category-values in the json_array.

    store_data = {'name': [], 'city': []}
    for item in json_array:
        store_data['name'].append(item['name'])
        store_data['city'].append(item['city'])
    # {'name': ['Mall of America', 'Tempe Marketplace'], 'city': ['Bloomington', 'Tempe']}
    
  3. For a "transposed" nested list where each sub-list is a "category" in json_array.

    store_list = list(store_data.values())
    # [['Mall of America', 'Tempe Marketplace'], ['Bloomington', 'Tempe']]
    
🌐
freeCodeCamp
freecodecamp.org β€Ί news β€Ί how-to-parse-json-in-python-with-examples
How to Parse JSON in Python – A Complete Guide With Examples
October 29, 2025 - This guide covers practical JSON parsing techniques you can use in your projects right away. Let’s get started! ... JSON represents data using a simple syntax with six data types: objects (key-value pairs), arrays, strings, numbers, Booleans, and null. When Python parses JSON, these types map directly to Python equivalents:
🌐
GitHub
github.com β€Ί oxylabs β€Ί python-parse-json
GitHub - oxylabs/python-parse-json: A tutorial for parsing JSON data with Python Β· GitHub
A tutorial for parsing JSON data with Python. Contribute to oxylabs/python-parse-json development by creating an account on GitHub.
Starred by 4 users
Forked by 4 users
Languages Β  Python
🌐
Veryfi
veryfi.com β€Ί home β€Ί engineering β€Ί parse json with python
Parse JSON with Python | Veryfi
May 19, 2023 - In addition to the json module, there are also several third-party libraries available to parse JSON with Python. One popular library is the jsonpath-rw library, which allows you to extract specific values from a JSON object using a JSONPath expression.
🌐
CodeSignal
codesignal.com β€Ί learn β€Ί courses β€Ί hierarchical-and-structured-data-formats β€Ί lessons β€Ί parsing-json-files-in-python
Parsing JSON Files in Python
In this lesson, you've learned to parse JSON files in Python using the json module. You've revisited JSON's structure, used the json.load() function to read JSON data from files, and accessed various elements within JSON data.
🌐
Reddit
reddit.com β€Ί r/pythonlearning β€Ί using python to parse a json object
r/PythonLearning on Reddit: Using Python to Parse a JSON Object
1 week ago -

Being retired, I’ve embarked on a project to keep my brain working as well as keeping my dwindling Python skills from completely disappearing.

I’ve been tinkering around with an API that allows me to grab time sequence weather data from a DOT weather station. As with most APIs the data is returned as a json object which to me (and Python) is a really ugly dictionary embedded with subsequent dictionaries that have keys and associated lists/tuples of values. For example one such dictionary has the AirTemp as the key with quarter hour values for as many hours I scrape. There are as many of these dictionaries as weather variables I choose to download : wind speed,direction, etc etc.

My approach to parsing the json object into something readable is to filter out each of the weather variable data into their own dictionary followed by creating a list of all the values in the data dictionary.

Finally, I zip those lists together and create a dictionary of the date/time variable as the key with the various weather variable values in a list associated to that specific date/time.

I’m just wondering if there might be different approach would be more efficient (and Pythonic). Sometimes I feel like I'm beating data into submission rather than processing it. This is the first time ever scripting to an API and parsing a json object.

import requests,json

weather_url = "https://api.weatherdata.com/v2/stations/timeseries?&token=MyToken&units=temp|f,speed|mph&stid=UTHEB&vars=wind_speed,wind_direction,air_temp&obtimezone=local&start=202603031700&end=202603032200"

response = requests.get(weather_url)
responseStatusCode = (response.status_code)

if responseStatusCode == 200:
    print(f"Connected to Weather Data Server; data incoming")
    jsonStr = response.json()

    tempDict = jsonStr['STATION'][0]#dictionary in json object with data
    obsDict = tempDict['OBSERVATIONS']#dictionary in station of data

    #begin list creation:

    dateList = obsDict['date_time']
    localDateList =[i.replace("T"," ").replace(":00-0700","-MT").replace("TimeStamp: ","") for i in dateList]

    airTempList = obsDict['air_temp_set_1']
    windSpeedList = obsDict['wind_speed_set_1']
    windDirectionList = obsDict['wind_direction_set_1']

    displayDict= {date: [speed,direction,temp]
    for date,speed,direction,temp in zip(localDateList,windSpeedList,windDirectionList,airTempList)}
    for key,value in displayDict.items():
        print(f"Date-Time: {key} WindSpeed MPH: {value[0]} WindDirection Degrees: {value[1]}  AirTemp: {value[2]}")
else:
    print(f"Unable to connect to Weather Data Server: try again later")
🌐
DevGenius
blog.devgenius.io β€Ί parsing-json-data-using-python-fd615f74e40f
Parsing JSON Data Using Python. My name is Jared Paubel, and this is my… | by Jay | Dev Genius
February 24, 2023 - One library that is popular for parsing through data is the pandas library, which is used for data manipulation and analysis. For example, we can load the same JSON data as a pandas dataframe, and use the head method to get just the first five results of the data set:
🌐
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.
🌐
Reddit
reddit.com β€Ί r/python β€Ί handling json files with ease in python
r/Python on Reddit: Handling JSON files with ease in Python
May 29, 2022 -

I have finished writing the third article in the Data Engineering with Python series. This is about working with JSON data in Python. I have tried to cover every necessary use case. If you have any other suggestions, let me know.

Working with JSON in Python
Data Engineering with Python series

🌐
Python.org
discuss.python.org β€Ί python help
How to parse different part of json file (Newbie here) - Python Help - Discussions on Python.org
September 27, 2021 - I have created a python code that extracts jitter, latency, link, packet loss, timestamp from json file to csv file. However, inside this json file, there are multiple tests done (e.g. bronek 1, bronek 2, bronek 3, etc.) that under these testings have pair keys of jitter, latency, link, packet ...
🌐
Reddit
reddit.com β€Ί r/learnpython β€Ί better way to parse insanely complex nested json data
r/learnpython on Reddit: Better way to parse insanely complex nested json data
July 16, 2024 -

Hi all,

Long time programmer here, but new to Python. This will be a long and, I think, complicated issue, so appreciate anyone who reads through it all and has any suggestions. I've looked up different ways to pull this data and don't seem to be making any progress. I'm sure there's a much better way.

I'm writing a program that will connect to our library to pull a list of everything we have checked out and I want to output a sorted list by due date and whether it has holds or not. I've got the code working to log in and pull a json data structure, but I cannot get it to export the data in the correct order. The json data is(to me) hideously complex with some data(due date) in one section and other data in another section. I'm able to pull the fields I want, but keeping them together is proving challenging.

For example, the title and subtitle are in the 'bibs/briefinfo' section with a key value of 'title' or 'subtitle'. Due Date is also in the 'checkouts' section with a key value of 'dueDate'. When I loop through them, though, the Titles are in one order, the due dates are in another order and the subtitles another.

I used BeautifulSoup because it's a webpage with json in it, so used BS to read the webpage.

I'm wanting to pull the following fields for each book so I can display the info for each book:

title, subtitle, contentType from briefinfo section

duedate from checkouts section

heldcopies and availablecopies from the availability section

Here's the pertinent section of my code:

soup = BeautifulSoup(index_page.text, 'html.parser')
            all_scripts = soup.find_all('script', {"type":"application/json"})

            for script in all_scripts:
                jsondata = json.loads(script.text)
                print(jsondata)
                
                output = []
                for i in item_generator(jsondata, "bibTitle"):
                    ans = {i}
                    print(i)
                    output.append(ans)

                for i in item_generator(jsondata, "dueDate"):
                    ans = {i}
                    output.append(ans)

                print("Subtitle----------------------")
                for i in item_generator(jsondata, "subtitle"):
                    ans = {i}
                    print(i)
                    output.append(ans)

print(output)

Here's the json output from my print statement so I can see what I'm working with. I tried to format it so it's easier to read. I removed a lot of other elements to keep the size down. Hopefully I didn't break any of the brackets.

{

'app':

{

'coreCssFingerprint': '123123123',

'coreAssets':

{

'cdnHost': 'https://xyz.com',

'cssPath': '/dynamic_stylesheet',

'defaultStylesheet': 'xyz.css'

},

},

'entities':

{

'listItems': {},

'cards': {},

'accounts':

{

'88888888':

  {
  'barcode': '999999999',
  'expiryDate': None, 
  'id': 88888888, 
  }

},

'shelves':

  {
  '88888888': 
  	{
  	'1111222222': 

{

'id': 1111222222,

'metadataId': 'S00A1122334',

'shelf': 'for_later',

'privateItem': True,

'dateAdded': '2023-12-30',

},

  	}
  }, 

'users':

  {
  '88888888': 
  	{ 
  	'accounts': \[88888888\], 
  	'status': 'A', 
  	'showGroupingDebug': False, 
  	'avatarUrl': '', 
  	'id': 88888888, 
  	}
  }, 
  'eventPrograms': {}, 
  'checkouts': 
  	{
  	'112233445566778899': 

{

'checkoutId': '112233445566778899',

'materialType': 'PHYSICAL',

'dueDate': '2024-08-26',

'metadataId': 'S99Z000000',

'bibTitle': "The Lord of the Rings"

},

  	'998877665544332211': 

{

'checkoutId': 998877665544332211',

'materialType': 'PHYSICAL',

'dueDate': '2024-08-26',

'metadataId': 'S88Y00000',

'bibTitle': 'The Lord of the Rings'

},

  	}, 
  'eventSeries': {}, 
  'catalogBibs': {},
  'bibs': 
  	{
  	'S88Y00000': 

{

'id': 'S88Y00000',

'briefInfo':

{

'superFormats': ['BOOKS', 'MODERN_FORMATS'],

'genreForm': [],

'callNumber': '123.456',

'authors': ['Tolkien, J.R.R.'],

'metadataId': 'S88Y00000',

'jacket':

{

'type': 'hardcover',

'local_url': None

},

'contentType': 'FICTION',

'format': 'BK',

'subtitle': 'The Two Towers',

'title': 'The Lord of the Rings',

'id': 'S88Y00000',

},

'availability':

{

'heldCopies': 0,

'singleBranch': False,

'metadataId': 'S88Y00000',

'statusType': 'AVAILABLE',

'totalCopies': 3,

'availableCopies': 2

}

},

'S77X12345':

{

'id': 'S77X12345',

'briefInfo':

{

'superFormats': ['BOOKS', 'MODERN_FORMATS'],

'genreForm': [],

'callNumber': '123.457',

'authors': ['Tolkien, J.R.R.'],

'metadataId': 'S77X12345',

'jacket':

{

'type': 'hardcover',

'local_url': None

},

'contentType': 'FICTION',

'format': 'BK',

'subtitle': 'The Fellowship of the Ring',

'title': 'The Lord of the Rings',

'id': 'S77X12345',

},

'availability':

{

'heldCopies': 0,

'singleBranch': False,

'metadataId': 'S77X12345',

'statusType': 'AVAILABLE',

'totalCopies': 2,

'availableCopies': 1

}

}

Anyone know of a better way to parse this data? Thanks!

Top answer
1 of 4
5
Two suggestions: First, when you want to print a json thing, you can do print(json.dumps(thing, indent=2)). This will apply indentation and newlines to make it clearer what the nested structure is. Second, the input data is what it is - but internal to your code you don't have to keep it that way. My suggestion would be to make a dataclass with the fields you care about, and write a classmethod for that that class to extract what you care about from the json. Then in your code, use instances of your class. I'm on my phone right now, but I'll edit with a small example of what I mean in a little bit. gross_nested_json = { 'books': [ { 'name': 'whatever', 'details1': { 'due_date': 'whenever', }, 'details2': { 'whatever_else': 'thing', } } ] } import dataclasses import typing as ty @dataclasses.dataclass class BookInfo: # If you're not familiar with these, google python dataclass, they're nice name: str due_date: str whatever: str @classmethod def from_gross_json(cls, gross_json: dict) -> ty.Self: return cls( name=gross_json['name'], due_date=gross_json['details1']['due_date'] whatever=gross_json['details2']['whatever_else'] ) books = [BookInfo.from_gross_json(gross_json) for gross_json in gross_nested_json['books'] You'll have to adjust for the pecularities of your particular input data, but if you make the data less gross for within your code consumption, it'll make the rest of your program nicer to write.
2 of 4
2
That's a rather awkward structure alright. Are the records to be linked by metadataId? [In]: for checkout in data['entities']['checkouts'].values(): print(checkout['bibTitle'], checkout['dueDate'], checkout['metadataId']) for bib in data['entities']['bibs'].values(): print(bib['briefInfo']['title'], bib['briefInfo']['subtitle'], bib['briefInfo']['metadataId']) print(bib['availability']['heldCopies'], bib['availability']['availableCopies']) [Out]: # The Lord of the Rings 2024-08-26 S99Z000000 # The Lord of the Rings 2024-08-26 S88Y00000 # The Lord of the Rings The Two Towers S88Y00000 # 0 2 # The Lord of the Rings The Fellowship of the Ring S77X12345 # 0 1
🌐
Reddit
reddit.com β€Ί r/learnpython β€Ί really struggling with parsing json and dictionaries
r/learnpython on Reddit: Really struggling with parsing json and dictionaries
June 18, 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
🌐
ReqBin
reqbin.com β€Ί code β€Ί python β€Ί g4nr6w3u β€Ί python-parse-json-example
How to parse a JSON with Python?
Nested JSON objects will also be processed and included in the dictionary (see example below). To parse a JSON file, use the json.load() paired method (without the "s"). In this Python Parse JSON example, we convert a JSON data string into a ...