1

In python, I am getting a JSON from an API call.

resp = requests.get(url)
resp.json()

I am going to use my MySQL vocabulary. This object I get is huge, with irregular structure (not all fields are available for each entry).

So I want to select in this JSON some fields and some entries based on values. Let's say that the JSON returns profiles of users, with the fields "name", "email", and "age".

I want to create a new small JSON having:

  • Only one field "email" - we remove the entries not having an email field.
  • Only when "age" = 15

While in SQL I would do it in 30 seconds, I haven't found how to do it in Python...

martineau
  • 119,623
  • 25
  • 170
  • 301
Vincent H
  • 11
  • 1
  • Use a `for` loop, test whether the entry in the list matches your criteria, and add it to the result list. – Barmar Nov 08 '18 at 17:19
  • `if "email" in entry and entry["age"] == 15: ...` – Barmar Nov 08 '18 at 17:20
  • You might want a [jmespath filter](http://jmespath.org/tutorial.html#filter-projections) – Bruce Becker Nov 08 '18 at 17:21
  • Can you be a bit more explicit on the code to use? It is super obvious I need a loop to review the entries, and an if. But it does not tell me what's the syntax. Thanks – Vincent H Nov 08 '18 at 17:30
  • @Barmar I don't see the connection with the duplicated topic you mentioned. Different case. – Vincent H Nov 08 '18 at 20:13
  • Maybe I'm misunderstanding. It seems like you just need to know how to access these fields. What you do with the data should be obvious once you get them. – Barmar Nov 08 '18 at 20:29
  • The most Pythonic way to filter your response is a list comprehension (over your response) that applies your filter conditions in its `if` part, and you formulate these conditions in a way that is tolerant (but rejecting) towards missing fields: `data = [ row for row in resp.json() if row.get("age", 0) == 15 and row.get("email") ]` – digitalarbeiter Nov 08 '18 at 20:35

1 Answers1

0

You could you list comprehension for that - I think syntax would be the most similar to SQL

[obj for obj in res.json() if obj.email is not None and obj.age=="15"]

or use more functional approach

def yourCustomFilter(obj):
    return obj.email is not None and obj.age=="15"

filter(resp.json(), yourCustomFilter)

or simple for each loop

filteredObjects = []
for obj in resp.json():
    if obj.email is not None and obj.age=="15":
        filteredObjects.append(obj)
sawim
  • 1,032
  • 8
  • 18