Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Python: Option to validate duplicate fields during json deserialization #20418

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

sersh4nt
Copy link

The issue

Proto:

syntax = "proto3";

package test;

message User {
  string first_name = 1 [json_name = "first_name"];
  string last_name = 2;
}

Code:

from google.protobuf.json_format import ParseDict
import test_pb2

data = {"first_name": "Aaron", "last_name": "Surname", "lastName": "Fake"}

message = ParseDict(data, test_pb2.User())

print(message)

Output:

first_name: "Aaron"
last_name: "Fake"

Why is this a problem?

This is a pretty unexpected behavior. Even using json_name cannot fully prevent one from using duplicate fields in json.

What about implementations in other languages?

protobuf-go features a specific check for duplicate fields.
This PR is created similarly to C# PR

What does this PR do?

This PR improves checks for fields already used during JSON parsing. Back to the example, the result will be as follows:

Code:

from google.protobuf.json_format import ParseDict
import test_pb2

data = {"first_name": "Aaron", "last_name": "Surname", "lastName": "Fake"}

message = ParseDict(data, test_pb2.User())

print(message)

Output:

Traceback (most recent call last):
  File "/Users/sersh4nt/Projects/protobuf/venv/lib/python3.12/site-packages/google/protobuf/json_format.py", line 597, in _ConvertFieldValuePair
    raise ParseError(
google.protobuf.json_format.ParseError: Message type "test.User" should not have multiple "lastName" fields at "User".

@sersh4nt sersh4nt requested a review from a team as a code owner February 20, 2025 18:30
@sersh4nt sersh4nt requested review from ericsalo and removed request for a team February 20, 2025 18:30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant