Thanks.
Am trying to get the particular key value from json data using python. logic is to call the function and function should return key (json output sometimes will be just 1 index data or sometime morethan 1 index data)
I was able to get the data and print them, it works fine in inside for loop but when I return back to main then am getting only one value. not sure if something to do with for loop.
json data :
[{
id: "587e569472",
hostname: "I-56BXX",
env: "Beta",
site: "I",
version: "2.0.0.38-1"},
{
id: "587e64472",
hostname: "I-56AXX",
env: "Beta",
site: "I",
version: "2.0.0.39-1"}]
main script :
def get_jsondata(url, hosts):
u = urllib2.urlopen(url)
json_object = json.load(u)
u.close
indexcount = len(json_object)
#print indexcount
#for i in json_object:
#print i['hostname']
if json_object == []:
print 'No Data!'
else:
for rows in json_object:
#print 'hostname:' + rows['hostname']
#print 'env:' + rows['env']
print 'hostname and its env:' + rows['hostname'] + " " + rows['env']
#return rows['hostname']
hosts = rows['hostname']
#print hosts
return (hosts)
#if __name__ == '__main__':
# main()
#main section
url = 'http://api.com/AppData/'
hosts = ""
hosts = get_jsondata(url, hosts)
#print "The required hostname " + str(hostname) + " and its env is " + str(venue)
print(hosts)
After running the script am getting output as :
hostname and its env:I-56BXX I
I-56BXX
I was trying to get both hostname return back to main so, output would be like
hostname and its env:I-56BXX I
hostname and its env:I-56AXX I
I-56BXX
I-56AXX
first 2 line from above output is from print stmt inside for loop and next 2 lines are from return data.
hosts = [h['hostname'] for h in json_object]