Skip to content

Commit 5ba6838

Browse files
committed
update per gemini review
1 parent 5011fca commit 5ba6838

1 file changed

Lines changed: 9 additions & 17 deletions

File tree

sdks/python/apache_beam/yaml/yaml_mapping.py

Lines changed: 9 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -229,40 +229,32 @@ def _expand_javascript_mapping_func(
229229
raise ValueError(
230230
"Javascript mapping functions require the 'quickjs' package.")
231231

232-
import json
233-
234232
if expression:
235-
source = '\n'.join(
236-
['function fn(json_row) {', ' const __row__ = JSON.parse(json_row);'] +
237-
[
238-
f' const {name} = __row__.{name};'
239-
for name in original_fields if name in expression
240-
] + [' return JSON.stringify(' + expression + ');'] + ['}'])
233+
source = '\n'.join(['function fn(__row__) {'] + [
234+
f' const {name} = __row__["{name}"];' for name in original_fields
235+
if name.isidentifier() and name in expression
236+
] + [' return (' + expression + ');'] + ['}'])
241237
js_func = _QuickJsCallable(source, "fn")
242238

243239
elif callable:
244240
# Wrap the callable in a named function to use quickjs.Function
245-
source = (
246-
f"function fn(json_row) {{ "
247-
f"const row = JSON.parse(json_row); "
248-
f"return JSON.stringify(({callable})(row)); }}")
241+
source = (f"function fn(row) {{ "
242+
f"return ({callable})(row); }}")
249243
js_func = _QuickJsCallable(source, "fn")
250244

251245
else:
252246
if not path.endswith('.js'):
253247
raise ValueError(f'File "{path}" is not a valid .js file.')
254248
udf_code = FileSystems.open(path).read().decode()
255249
bridge_source = (
256-
udf_code + f"\nfunction bridge_fn(json_row) {{ "
257-
f"return JSON.stringify({name}(JSON.parse(json_row))); }}")
250+
udf_code + f"\nfunction bridge_fn(row) {{ "
251+
f"return {name}(row); }}")
258252
js_func = _QuickJsCallable(bridge_source, "bridge_fn")
259253

260254
def js_wrapper(row):
261255
row_as_dict = py_value_to_js_dict(row)
262-
row_json = json.dumps(row_as_dict)
263256
try:
264-
js_result_json = js_func(row_json)
265-
js_result = json.loads(js_result_json)
257+
js_result = js_func(row_as_dict)
266258
except Exception as exn:
267259
raise RuntimeError(
268260
f"Error evaluating javascript expression: {exn}") from exn

0 commit comments

Comments
 (0)