Hack Forums
[Python] I need help pulling/search data from Json - Printable Version

+- Hack Forums (https://hackforums.net)
+-- Forum: Tech (https://hackforums.net/forumdisplay.php?fid=444)
+--- Forum: Coding (https://hackforums.net/forumdisplay.php?fid=151)
+---- Forum: Software Development (https://hackforums.net/forumdisplay.php?fid=118)
+---- Thread: [Python] I need help pulling/search data from Json (/showthread.php?tid=5786243)



I need help pulling/search data from Json - koolkid - Jan 17, 2018

hello  below is my code
PHP Code

<?php 
import urllib
.request
import json
##inp = input("enter website address : ")
##url= urllib.request.urlopen("http://freegeoip.net/json/{}".format(inp))
url= urllib.request.urlopen("http://data.gov.jm/api/action/datastore/search.json?resource_id=da5f0429-18ba-4d38-bd03-26171b81309c&limit=1")

data = json.loads(url.read().decode())
#print('IP : {}'.format(data['ip']))
print(data)
#print('Division : {}'.format(data['Clarendon']))
#print('Year : {}'.format(data[2007]))
#print('Fatalities : {}'.format(data['']))
#print(data["Division"])
if data[{"Division"}] == "Clarendon":
 
   print(data[{"Division"}])
 
   print(data[{"Fatalities"}])
 
    
i want to be able to search for specific data in this json api


RE: I need help pulling/search data from Json - Anxuein - Jan 17, 2018

You get a list of results from that JSON result with:
PHP Code

<?php 
data
["result"]["records"] 

I assume there can be more than one result; however, to get the first result, you'd call it like such:
PHP Code

<?php 
data
["result"]["records"][0] 
That will be a dictionary containing the following keys:
Code
Division
Fatal accidents
Fatalities
Year

If you want to loop through to find a specific division, you'd use something like this:
PHP Code

<?php 
for division in data["result"]["records"]:
    print(
division["Division"])
    if 
division["Division"] == "whatever":
        
# do stuff