Fix the check that lists a struct's JSON keys

Review the AI's codeEasy12 min

Your task

Your Go service encodes its User struct straight into API responses: email and role never arrive, and the password always does. The team is adding a response allowlist and wants a check that lists the keys a struct really sends.

An assistant wrote safe_json_keys(field_lines, allowed_keys). It is in the editor. It has a bug. Find it and fix it.

Input and output:

  • field_lines: the struct's fields in order, one string each: "FieldName|tag". The tag is the text inside json:"...", such as created_at,omitempty. An empty tag means the field has no tag.
  • allowed_keys: the JSON keys the response may contain.
  • Return the JSON keys that get sent, as a list of strings.

Rules the tests check:

  • Skip a line that does not split on | into exactly 2 parts, or whose field name is empty.
  • Skip a field whose name does not start with a capital letter from A to Z. Go calls these fields unexported, and encoding/json never writes them.
  • Skip a field whose tag is exactly "-".
  • The key is the part of the tag before the first comma. When the tag is empty, or that part is empty (as in ",omitempty"), the key is the field name exactly as written. So the tag "-," gives the key "-".
  • Keep a key only when it is in allowed_keys. The match is exact and case sensitive.
  • Return the keys in field order. When two kept fields give the same key, keep only the first.
  • No fields returns an empty list.

Examples

safe_json_keys(field_lines: list[str], allowed_keys: list[str]) -> list[str]
Example 1
Inputsafe_json_keys(["ID|", "email|", "Role|-", "Password|password", "CreatedAt|created_at"], ["ID", "email", "Role", "password", "created_at"])
Output["ID", "password", "created_at"]
Example 2
Inputsafe_json_keys(["ID|id", "Email|email", "Role|role", "PasswordHash|-", "CreatedAt|created_at"], ["id", "email", "role", "created_at"])
Output["id", "email", "role", "created_at"]
Example 3
Inputsafe_json_keys(["ID|id", "Password|password"], ["id"])
Output["id"]