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 OverflowInstead 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']
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()
How to print specific value from specific key from JSON in Python - Stack Overflow
How to select specific key/value of an object in json via python - Stack Overflow
python - extract a specific key / value from json file by a variable - Stack Overflow
python JSON only get keys in first level - Stack Overflow
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)
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'])
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']
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())
Just do a simple .keys()
>>> dct = {
... "1": "a",
... "3": "b",
... "8": {
... "12": "c",
... "25": "d"
... }
... }
>>>
>>> dct.keys()
['1', '8', '3']
>>> for key in dct.keys(): print key
...
1
8
3
>>>
If you need a sorted list:
keylist = dct.keys() # this is of type `dict_key`, NOT a `list`
keylist.sort()
And if you want them as simple list, do this:
list(dct_instance.keys())
for key in data.keys():
print key
If you want to iterate over both keys and values of the dictionary, do this:
for key, value in data.items():
print(key, value)
What error is it giving you?
If you do exactly this:
data = json.loads('{"lat":444, "lon":555}')
Then:
data['lat']
SHOULD NOT give you any error at all.
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.
data["suggestions"] is a list of dictionaries. You either need to provide an index (ie data["suggestions"][0]["entities"]) or use a loop:
for suggestion in data["suggestions"]:
print suggestion["entities"]
Keep in mind that "entities" is also a list, so the same will apply:
for suggestion in data["suggestions"]:
for entity in suggestion["entities"]:
print entity["caption"]
If you see data within suggestions, is an array, so you should read like below:
print data["suggestions"][0]["entities"]