This Question have 3 answers right now.

Python - Filter a dict JSON response to send back only two values or convert to a string?

Question!

I am manipulating a URL in Python that calls an API and gets a valid result in JSON.

I only need the 'latitude' and 'longitude' provided by [result]

But, I cannot seem to find any good way to handle sending dict values back.

I've tried to convert the JSON to a string, but as my end goal is to append the latitude and longitude to another URL, this seems silly?

Have been searching around, and seems parsing DICT a common issue.

Can anyone point me in the right direction?

My code (that ran)

import urllib2
import json
Postcode = raw_input("Hello hello hello, what's your postcode..?  ")
PostcodeURL = 'https://api.postcodes.io/postcodes/' + Postcode
json_str = urllib2.urlopen(PostcodeURL).read()
d = json.loads(json_str)
print(d)

The output looks like this:

{u'status': 200, u'result': {u'eastings': 531025, u'outcode': u'N8', u'admin_county': None, u'postcode'


Answers

You can access your JSON object exactly like a dictionary. So to get the latitude and longitude from your result, you can use:

lat, long = d[result][latitude], d[result][longitude]

Load these into strings, do your error checking, and then append them into your new URL.



You got a nested dictionary back, so access it's values using the right keys:

d = json.loads(json_str)
lat, long = d['result']['latitude'], d['result']['longitude']
newurl = url + '?' + 'lat=' + lat + '&lon=' + lon

Please provide full output and url format for exact code.

By : Uriel Eli


If I am reading this correctly, Message would contain a List<MessageUser>.

If that's the case then this should get you close:

var List<Message> messages = 
    ( from m 
      in db.Messages 
      where 
          m.UserID == userid || m.MessageUsers.Any(mu => mu.UserID == userID) 
      select m).ToList();
By : Sam Axe


Video about Python - Filter a dict JSON response to send back only two values or convert to a string?