Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Extract Filtered Events from JSON

EasyPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Extract Filtered Events from JSON. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

Acme Analytics stores application logs as a large JSON payload. Write a function that parses the payload and extracts only the events that match a target event type and optional attribute filters.

Given a JSON string representing an object with an events array, return a list of simplified event objects for every valid event whose type matches target_type and whose key-value pairs in required_attrs are all present inside the event's attributes object.

Formal Specification

Implement:

  • payload: a JSON string
  • target_type: a string
  • required_attrs: a dictionary of required attribute filters

Return a list of dictionaries. Each output dictionary must contain:

  • id: event id
  • timestamp: event timestamp
  • user_id: user id if present, otherwise null

Ignore malformed event entries, events missing required top-level fields (id, type, timestamp), and events whose attributes field is not an object.

Constraints

  • 1 <= len(events) <= 10^5
  • The JSON payload may be invalid; return an empty list in that case
  • Each valid event is a JSON object
  • Required top-level fields are id, type, and timestamp
  • required_attrs may be empty, in which case all events of the target type qualify

Function Signature

def extract_events(payload, target_type, required_attrs):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output