Created
June 13, 2021 19:31
-
-
Save tcurvelo/ecb2bb305653ceac1cc73fd5944b7fdd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import jmespath | |
def remap_fields(fieldmap, data, loader=None, *, jmes=True, **defaults): | |
'''Map data. | |
>>> remap_fields({'price': 'productPrice'}, {'productPrice': 5.00}) | |
{'price': 5.00} | |
>>> remap_fields({'price': ['producPrice', 'finalPrice']}, {'finalPrice': 5.00}) | |
{'price': 5.00} | |
WARNING: JMESPath does not differentiate between absent and null fields. | |
This function will regard null fields as absent when using JMESPath. | |
''' | |
out = {} | |
for ours, theirs in fieldmap.items(): | |
if not isinstance(theirs, (list, tuple)): | |
theirs = [theirs] | |
for their in theirs: | |
if jmes: | |
val = jmespath.search(their, data) | |
if val is not None: | |
break | |
elif their in data: | |
val = data[their] | |
break | |
else: | |
val = defaults.get(ours) | |
out[ours] = val | |
if loader: | |
loader.add_value(ours, val) | |
return out |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment