Read top-level package.json version metadata defensively
Direct answer
A defensive package manifest reader first separates parsing from interpretation. json.loads either produces an object or raises JSONDecodeError; after that boundary, the scanner accepts only a string in the top-level version member. A JSON number, array, string, or null is syntactically valid, but this reader requires an object before it accesses version. The fixture asserts a normal string version, a wrong type, and malformed JSON. It does not search workspaces, nested dependencies, or publish configuration. Those are different package-management questions. The reported unavailable states tell a caller to inspect metadata rather than inventing a version from partial input.
Complete example
import json
def manifest_version(text: str) -> str | None:
try:
document = json.loads(text)
if not isinstance(document, dict):
return None
value = document.get("version")
except json.JSONDecodeError:
return None
return value if isinstance(value, str) else None
assert manifest_version('{"version": "2.0.0"}') == "2.0.0"
assert manifest_version('{"version": 2}') is None
assert manifest_version('{') is None
assert manifest_version('[]') is None
print("version=2.0.0 number=unavailable malformed=unavailable")
Expected stdout:
version=2.0.0 number=unavailable malformed=unavailable
Sources
Prepared with AI assistance. The example uses synthetic data; its stated limits apply.
Comments
Post a Comment