Instead of for key, value in jdata:, use for key, value in jdata.items(): like this:

for key, value in data.items():
    pprint("Key:")
    pprint(key)

Take a look at the docs for dict:

items():

Return a new view of the dictionary’s items ((key, value) pairs).

EDIT: If you want to get all of the nested keys and not just the top level ones, you could take an approach like those suggested in another answer like so:

def get_keys(dl, keys_list):
    if isinstance(dl, dict):
        keys_list += dl.keys()
        map(lambda x: get_keys(x, keys_list), dl.values())
    elif isinstance(dl, list):
        map(lambda x: get_keys(x, keys_list), dl)

keys = []
get_keys(jdata, keys)

print(keys)
# [u'a', u'inLanguage', u'description', u'priceCurrency', u'geonames_address', u'price', u'title', u'availabl', u'uri', u'seller', u'publisher', u'a', u'hasIdentifier', u'hasPreferredName', u'uri', u'fallsWithinState1stDiv', u'score', u'fallsWithinCountry', u'fallsWithinCountyProvince2ndDiv', u'geo', u'a', u'hasType', u'label', u'a', u'label', u'a', u'uri', u'hasName', u'a', u'label', u'a', u'uri', u'hasName', u'a', u'label', u'a', u'uri', u'lat', u'lon', u'a', u'address', u'a', u'name', u'a', u'description', u'a', u'name', usury']

print(list(set(keys)))    # unique list of keys
# [u'inLanguage', u'fallsWithinState1stDiv', u'label', u'hasName', u'title', u'hasPreferredName', u'lon', u'seller', u'score', u'description', u'price', u'address', u'lat', u'fallsWithinCountyProvince2ndDiv', u'geo', u'a', u'publisher', u'hasIdentifier', u'name', u'priceCurrency', u'geonames_address', u'hasType', u'availabl', u'uri', u'fallsWithinCountry']
Answer from Mike Covington on Stack Overflow
Top answer
1 of 2
22

Instead of for key, value in jdata:, use for key, value in jdata.items(): like this:

for key, value in data.items():
    pprint("Key:")
    pprint(key)

Take a look at the docs for dict:

items():

Return a new view of the dictionary’s items ((key, value) pairs).

EDIT: If you want to get all of the nested keys and not just the top level ones, you could take an approach like those suggested in another answer like so:

def get_keys(dl, keys_list):
    if isinstance(dl, dict):
        keys_list += dl.keys()
        map(lambda x: get_keys(x, keys_list), dl.values())
    elif isinstance(dl, list):
        map(lambda x: get_keys(x, keys_list), dl)

keys = []
get_keys(jdata, keys)

print(keys)
# [u'a', u'inLanguage', u'description', u'priceCurrency', u'geonames_address', u'price', u'title', u'availabl', u'uri', u'seller', u'publisher', u'a', u'hasIdentifier', u'hasPreferredName', u'uri', u'fallsWithinState1stDiv', u'score', u'fallsWithinCountry', u'fallsWithinCountyProvince2ndDiv', u'geo', u'a', u'hasType', u'label', u'a', u'label', u'a', u'uri', u'hasName', u'a', u'label', u'a', u'uri', u'hasName', u'a', u'label', u'a', u'uri', u'lat', u'lon', u'a', u'address', u'a', u'name', u'a', u'description', u'a', u'name', usury']

print(list(set(keys)))    # unique list of keys
# [u'inLanguage', u'fallsWithinState1stDiv', u'label', u'hasName', u'title', u'hasPreferredName', u'lon', u'seller', u'score', u'description', u'price', u'address', u'lat', u'fallsWithinCountyProvince2ndDiv', u'geo', u'a', u'publisher', u'hasIdentifier', u'name', u'priceCurrency', u'geonames_address', u'hasType', u'availabl', u'uri', u'fallsWithinCountry']
2 of 2
6

You should use either dict.items() or dict.iteritems() in for key, value in jdata

So, it should be either

for key, value in jdata.items():

OR

for key, value in jdata.iteritems():

for python3 and python2 respectively.

See answers on this question to know the difference between the two: What is the difference between dict.items() and dict.iteritems()?

If you only need to iterate over keys of the dictionary, you can even try dict.keys() or dict.iterkeys()

🌐
DEV Community
dev.to › bluepaperbirds › get-all-keys-and-values-from-json-object-in-python-1b2d
Get all keys and values from json object in Python - DEV Community
January 12, 2021 - In our json file there's a header ... data = json.load(jsonFile) jsonData = data["emp_details"] for x in jsonData: keys = x.keys() print(keys) values = x.values() print(values)...
Discussions

How to print specific value from specific key from JSON in Python - Stack Overflow
I wrote 2 functions so I can get champion ID knowing champion Name but then I wanted to get champion Name knowing champion ID but I cannot figure it out how to extract the name because of how the d... More on stackoverflow.com
🌐 stackoverflow.com
November 20, 2018
How to select specific key/value of an object in json via python - Stack Overflow
Here is the working code for you: ... print (resp['device'][0]['username']) 2019-01-12T14:40:07.023Z+00:00 ... Find the answer to your question by asking. Ask question ... See similar questions with these tags. ... Stack Overflow chat opening up to all users in January; Stack Exchange chat... 0 Extracting Key from multilevel (scraped) complex structure json file in python · 1 How to read list in json file from python script · 7 Get the value of specific JSON element ... More on stackoverflow.com
🌐 stackoverflow.com
python - extract a specific key / value from json file by a variable - Stack Overflow
As shown you then access the contents ... will be keys in that dictionary. If the JSON contents are in a file you can open it like any other file in Python and pass the file object's name to the json.load() function: #!/bin/python import json with open("some_file.json") as f: some_stuff = json.load(f) print ' ... More on stackoverflow.com
🌐 stackoverflow.com
python JSON only get keys in first level - Stack Overflow
I have a very long and complicated json object but I only want to get the items/keys in the first level! ... I want to get 1,3,8 as result! ... No, it doesn't. It prints the keys, and the values which themselves include the sub-dictionaries. More on stackoverflow.com
🌐 stackoverflow.com
🌐
Stack Overflow
stackoverflow.com › questions › 53387867 › how-to-print-specific-value-from-specific-key-from-json-in-python
How to print specific value from specific key from JSON in Python - Stack Overflow
November 20, 2018 - def requestChampionData(championName): name = championName.lower() name = name.title() URL = "http://ddragon.leagueoflegends.com/cdn/8.23.1/data/en_US/champion/" + name + ".json" response = requests.get(URL) return response.json() def championID(championName): championData = requestChampionData(championName) championID = str(championData['data'][championName]['key']) return championID ... It's rarely (like, never) a good idea to duplicate data in a database, JSON included. I suggest restructuring your JSON so that the champion name is in the innermost block with the rest of the data. That will meet both (and other) methods of accessing the data. ... since python values are passed by reference you can make a new dict with keys as the champion id pointing to the values of the previous dict, that way you dont duplicate too much data.
Top answer
1 of 3
4

You can use list comprehension and dict like this:

device_disco["device"] =[dict(username=k1["username"],password=k1["password"],ip=k1["ip"]) for k1 in 
device_disco["device"]]

jsonData = json.dumps(device_disco)
print (jsonData)

in your code:

import requests
import json

#API request details
url = 'api url'
data = '{"service":"ssh", "user_id":"0", "action":"read_by_user", 
"user":"D2", "keyword":"NULL"}'
headers = {"Content-Type": "application/json"}

#Making http request
response = requests.post(url,data=data,headers=headers,verify=False)
print(response)

#Json string
json_disco = response.text
print(type(json_disco))
print(json_disco)

#Decode response.json() method to a python dictionary and use the data
device_disco = response.json()
print(type(device_disco))
print(device_disco)
device_disco["device"] =[dict(username=k1["username"],password=k1["password"],ip=k1["ip"]) for k1 in 
device_disco["device"]]

jsonData = json.dumps(device_disco)


with open('devices.json', 'w') as fp:
json.dump(jsonData, fp, indent=4, sort_keys=True)
2 of 3
-2

Try this working code:

import json
import sys

data={
   "status": "SUCCESS",
   "device": [
         {
             "model":"XXXX-A",
             "username": "login1",
             "ip": "10.10.10.1",
             "password": "123",
             "device_type": "cisco_ios"
         },
         {
             "model":"XXXX-A",
             "username": "login2",
             "ip": "10.10.10.2",
             "password": "456",
             "device_type": "cisco_ios"
         },
         {
             "model":"XXXX-A",
             "username": "login3",
             "ip": "10.10.10.3",
             "password": "test",
             "device_type": "cisco_ios"
         }
    ]
}
json_str = json.dumps(data)
resp = json.loads(json_str)
print (resp['device'][0]['username'])
🌐
Medium
medium.com › @sharath.ravi › python-function-to-extract-specific-key-value-pair-from-json-data-7c063ecb5a15
Python function to extract specific key value pair from json data. | by Sharath Ravi | Medium
April 6, 2023 - The function first uses the json.loads method to convert the json_data string into a Python dictionary. It then uses the dictionary method get to retrieve the value associated with the specified key. If the key is not found in the dictionary, the method returns None. Here’s an example of how you could use this function: # Example JSON data json_data = '{"name": "John Doe", "age": 35, "city": "New York"}' # Extract the value associated with the "age" key age = extract_key_value(json_data, "age") # Print the result print(age) # Output: 35 ·
Top answer
1 of 3
4

You could do something along these lines:

import json

j='''{ "hosts":  {
             "example1.lab.com" : ["mysql", "apache"],
             "example2.lab.com" : ["sqlite", "nmap"],
             "example3.lab.com" : ["vim", "bind9"]
             }
}'''

specific_key='example2'

found=False
for key,di in json.loads(j).iteritems():    # items on Py 3k
    for k,v in di.items():
        if k.startswith(specific_key):
            found=True
            print k,v
            break
    if found:
        break 

Or, you could do:

def pairs(args):
    for arg in args:
        if arg[0].startswith(specific_key):
            k,v=arg
            print k,v

json.loads(j,object_pairs_hook=pairs)  

Either case, prints:

example2.lab.com [u'sqlite', u'nmap']
2 of 3
1

If you have the JSON in a string then just use Python's json.loads() function to load JSON parse the JSON and load its contents into your namespace by binding it to some local name

Example:

#!/bin/env python
import json
some_json = '''{ "hosts":  {
         "example1.lab.com" : ["mysql", "apache"],
         "example2.lab.com" : ["sqlite", "nmap"],
         "example3.lab.com" : ["vim", "bind9"]
         }
}'''
some_stuff = json.loads(some_json)
print some_stuff['hosts'].keys()

---> [u'example1.lab.com', u'example3.lab.com', u'example2.lab.com']

As shown you then access the contents of some_stuff just as you would any other Python dictionary ... all the top level variable declaration/assignments which were serialized (encoded) in the JSON will be keys in that dictionary.

If the JSON contents are in a file you can open it like any other file in Python and pass the file object's name to the json.load() function:

#!/bin/python
import json

with open("some_file.json") as f:
    some_stuff = json.load(f)

print ' '.join(some_stuff.keys())
Find elsewhere
🌐
YouTube
youtube.com › watch
How to Print a Specific Key from a JSON File in Python - YouTube
Learn how to extract and print specific keys from a JSON file using Python. This guide provides clear steps and code examples to assist you.---This video is ...
Published: March 24, 2025
Views: 8
🌐
GitHub
gist.github.com › jakekara › 6170372a471f009e39cb82d5e105d3e3
print the keys from any level of a json file · GitHub
print the keys from any level of a json file · Raw · jsonkeys.py · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
🌐
Like Geeks
likegeeks.com › home › python › how to get json value by key in python
How To Get JSON Value by Key in Python
You can access these values by ... subscription_plan) ... By converting the JSON string to a Python dictionary using json.loads(), you can retrieve any value by simply referencing its key....
🌐
Plain English
plainenglish.io › home › blog › python › extracting specific keys/values from a messed-up json file (python)
Extracting Specific Keys/Values From A Messed-Up JSON File (Python)
August 20, 2022 - def extract(data, keys): out = [] queue = [data] while len(queue) > 0: current = queue.pop(0) if type(current) == dict: for key in keys: # CHANGE THIS BLOCK if key in current: out.append({key:current[key]}) for val in current.values(): if type(val) in [list, dict]: queue.append(val) elif type(current) == list: queue.extend(current) return outx = extract(data, ["videoID"]) print(x)
🌐
IT trip
en.ittrip.xyz › python
Comprehensive Guide on Accessing Specific Keys from JSON Files in Python | IT trip
November 15, 2024 - To convert a Python data structure to a JSON string, use the json.dumps() function. import json json_string = '{"name": "John", "age": 30, "city": "New York"}' data = json.loads(json_string) print(data) json_output = json.dumps(data) ...
🌐
Python
docs.python.org › 3.3 › library › json.html
19.2. json — JSON encoder and decoder — Python 3.3.7 documentation
If sort_keys is True (default False), ... by key; this is useful for regression tests to ensure that JSON serializations can be compared on a day-to-day basis. If indent is a non-negative integer or string, then JSON array elements and object members will be pretty-printed with that ...
🌐
PYnative
pynative.com › home › python › json › python check if key exists in json and iterate the json array
Python Check if key exists in JSON and iterate the JSON array
May 14, 2021 - import json sampleJson = """{ "class":{ "student":{ "name":"jhon", "marks":{ "physics":70, "mathematics":80 } } } }""" print("Checking if nested JSON key exists or not") sampleDict = json.loads(sampleJson) if 'marks' in sampleDict['class']['student']: print("Student Marks are") print("Printing nested JSON key directly") print(sampleDict['class']['student']['marks'])Code language: Python (python) Run ·
🌐
Reddit
reddit.com › r/learnpython › list all json keys in a file to identify database column names from a file using python
r/learnpython on Reddit: List all JSON keys in a file to identify database column names from a file using Python
July 9, 2022 -

I am learning Python, and in particular, working with JSON and sqlite in Python. Ultimately I plan to use Python to load the JSON into a sqlite database.

Here is the question: Is there a way in to list all of the keys from a JSON file (not from a string) using Python? I want a list of all of the keys so I can determine what columns I will need/use in my sqlite table(s), without having to manually read the file and make a list.

BTW, this is something along the lines of using INFORMATION_SCHEMA.COLUMNS in SQL Server, or the FINDALL in Python for XML.

All of this is for personal learning, so I'm not looking to use other technologies, I'm sticking to Python, JSON, and sqlite on purpose.