Skip to content

Commit

Permalink
Merge pull request #70 from lsst/tickets/DM-41267
Browse files Browse the repository at this point in the history
DM-41267: Allow header text files to be in JSON format
  • Loading branch information
timj authored Oct 24, 2023
2 parents 0978aab + 78e3a55 commit b8aeb2f
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 5 deletions.
6 changes: 3 additions & 3 deletions python/astro_metadata_translator/file_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,8 +127,8 @@ def read_basic_metadata_from_file(
Parameters
----------
file : `str`
Name of file to read. Can be FITS or YAML. YAML must be a simple
top-level dict.
Name of file to read. Can be FITS, YAML or JSON. YAML or JSON must be
a simple top-level dict.
hdrnum : `int`
Header number to read. Only relevant for FITS. If greater than 1
it will be merged with the primary header. If a negative number is
Expand All @@ -149,7 +149,7 @@ def read_basic_metadata_from_file(
The header as a dict. Can be `None` if there was a problem reading
the file.
"""
if file.endswith(".yaml"):
if file.endswith(".yaml") or file.endswith(".json"):
try:
md = read_test_file(
file,
Expand Down
2 changes: 1 addition & 1 deletion python/astro_metadata_translator/headers.py
Original file line number Diff line number Diff line change
Expand Up @@ -351,7 +351,7 @@ def _find_from_resource(
Name of resource read. `None` if no corrections found.
"""
if package is not None and resource_root is not None:
resource_path = resources.files(package).joinpath(resource_root, target_file) # type: ignore
resource_path = resources.files(package).joinpath(resource_root, target_file)
if resource_path.is_file():
resource_uri = f"resource://{package}/{posixpath.join(resource_root, target_file)}"
log.debug("Applying header corrections from package resource %s", resource_uri)
Expand Down
9 changes: 8 additions & 1 deletion python/astro_metadata_translator/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

__all__ = ("read_test_file", "MetadataAssertHelper")

import json
import os
import pickle
import warnings
Expand Down Expand Up @@ -83,7 +84,13 @@ def read_test_file(filename: str, dir: str | None = None) -> MutableMapping[str,
if dir is not None and not os.path.isabs(filename):
filename = os.path.join(dir, filename)
with open(filename) as fd:
header = yaml.load(fd, Loader=Loader)
if filename.endswith(".yaml"):
header = yaml.load(fd, Loader=Loader)
elif filename.endswith(".json"):
header = json.load(fd)
else:
raise RuntimeError(f"Unrecognized file format: {filename}")

# Cannot directly check for Mapping because PropertyList is not one
if not hasattr(header, "items"):
raise ValueError(f"Contents of YAML file {filename} are not a mapping, they are {type(header)}")
Expand Down

0 comments on commit b8aeb2f

Please sign in to comment.