0

I am using simplejson

try:
    import json
except ImportError:
    import simplejson as json

def query_reviews (query):
    url = "http://......."
    response = urllib2.urlopen(url) 
    values=json.loads(response)

Now i want to take out specific value out of the output what i get.

So how can i do this? I have already searched a lot but not getting my issue resolved.Kindly help me out.

2
  • I think I've fixed your formatting. Please check to ensure it is accurate
    – Andy
    Feb 13, 2015 at 4:49
  • which value do you want to get, please give an example Feb 13, 2015 at 4:54

3 Answers 3

0

It depends on the json format

if it's an array, this will work

try:
import json
import urllib2
except ImportError:
    import simplejson as json

def query_reviews ():
    url = "https://raw.githubusercontent.com/twitter/typeahead.js/gh-pages/data/countries.json"
    response = urllib2.urlopen(url)
    values=json.loads(response.read())
    needle = 'Yemen'
    for value in values:
        if value == needle:
            print 'Found it!'
            print value

query_reviews()

If it's a dictionary use values['key'] like so:

try:
    import json
    import urllib2
except ImportError:
    import simplejson as json

def query_reviews ():
    url = "https://raw.githubusercontent.com/Bitergia/apache-cloudstack-dashboard/master/data/json/-its-dom-top-closers.json"
    response = urllib2.urlopen(url)
    values=json.loads(response.read())
    print values['id']

query_reviews()
0

I completely depends on the JSON you loaded. If it's a dict, the value is imported into a Python dict.

# JSON is {"game": "pacman", "year": 1988, "highscore": 123456}
print values['highscore']

If you have a complex hierarchy, that will be a dict of dicts.

# JSON is {"games": {"pacman": {"year": 1988, "highscore": 123456}},
#                   {"defender": {"highscore": 345798, "year": 1983}}, ...
print values['games']['pacman']['highscore']

If there are lists involved, you just index.

# JSON is [ {"game": "pacman", "year": 1988, "highscore": 123456},
#           {"game:" "defender", "highscore": 345678", "year": 1983}, ...
print values[0]['highscore']
0

The other answers are good; it may help to start with

pprint.pprint(values)  # after 'import pprint'

... and that will show you what the data you are getting looks like.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.