-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Description
Problem
I'm new to pydantic.
I was reading the documentation about parse_file,
parse_file()
like parse_raw() but for files; cf. helper function
Based on this, I assumed you use it like:
with open('myfile.json', 'r') as f:
MyModel.parse_file(f)
Which means you can use it with BytesIO or StringIO.
But that's not the case. It takes a file path, not a file-like object.
Solution
In the "Model Properties" section, change
parse_file()
like parse_raw() but for files; cf. helper function
to
parse_file()
like parse_raw() but for file paths; cf. helper function
In the helper function section, change
parse_file: this reads a file and passes the contents to parse_raw. If content_type is omitted, it is inferred from the file's extension.
to
parse_file: this takes in a file path and reads the file, then passes the contents to parse_raw. If content_type is omitted, it is inferred from the file's extension.
Then append to the code sample to provide an example of parse_file:
file_path = 'data.json'
with open(file_path, 'w') as f:
f.write('{"id": 123, "name": "James"}')
m = user.parse_file(file_path)