fix: resolve JSON.parse precision issue causing 'list index out of range' error in Code node #21200

pull/21253/head
baonudesifeizhai 11 months ago
parent 6b1ad634f1
commit 3d71246b3d

@ -11,16 +11,57 @@ class NodeJsTemplateTransformer(TemplateTransformer):
// declare main function // declare main function
{cls._code_placeholder} {cls._code_placeholder}
// decode and prepare input object try {{
var inputs_obj = JSON.parse(Buffer.from('{cls._inputs_placeholder}', 'base64').toString('utf-8')) // decode and prepare input object
var inputs_obj = JSON.parse(Buffer.from('{cls._inputs_placeholder}', 'base64').toString('utf-8'))
// execute main function // Preprocess inputs to handle number precision issues
var output_obj = main(inputs_obj) function preprocessInputs(obj) {{
if (typeof obj === 'object' && obj !== null) {{
for (var key in obj) {{
if (obj.hasOwnProperty(key)) {{
if (typeof obj[key] === 'string') {{
// Try to parse string as number if it looks like a number
var num = parseFloat(obj[key]);
if (!isNaN(num) && obj[key].trim() === num.toString()) {{
obj[key] = num;
}}
}} else if (typeof obj[key] === 'object') {{
preprocessInputs(obj[key]);
}}
}}
}}
}}
return obj;
}}
// Preprocess inputs
inputs_obj = preprocessInputs(inputs_obj);
// convert output to json and print // execute main function
var output_json = JSON.stringify(output_obj) var output_obj = main(inputs_obj)
var result = `<<RESULT>>${{output_json}}<<RESULT>>`
console.log(result) // Handle precision numbers properly in JSON.stringify
var output_json = JSON.stringify(output_obj, function(key, value) {{
// Ensure numbers are properly serialized
if (typeof value === 'number') {{
// Handle very small numbers that might cause precision issues
if (Math.abs(value) < 1e-1 && Math.abs(value) > 0) {{
// Convert to string to preserve precision
return value.toString();
}}
}}
return value;
}})
var result = `<<RESULT>>${{output_json}}<<RESULT>>`
console.log(result)
}} catch (error) {{
console.error('JavaScript execution error:', error.message)
// Provide more detailed error information
var errorResult = `<<RESULT>>{{"error": "JavaScript execution failed: " + error.message}}<<RESULT>>`
console.log(errorResult)
}}
""" """
) )
return runner_script return runner_script

@ -28,7 +28,7 @@ class TemplateTransformer(ABC):
def extract_result_str_from_response(cls, response: str): def extract_result_str_from_response(cls, response: str):
result = re.search(rf"{cls._result_tag}(.*){cls._result_tag}", response, re.DOTALL) result = re.search(rf"{cls._result_tag}(.*){cls._result_tag}", response, re.DOTALL)
if not result: if not result:
raise ValueError("Failed to parse result") raise ValueError(f"Failed to parse result: no result tag found in response. Response: {response[:200]}...")
return result.group(1) return result.group(1)
@classmethod @classmethod
@ -39,13 +39,24 @@ class TemplateTransformer(ABC):
:return: :return:
""" """
try: try:
result = json.loads(cls.extract_result_str_from_response(response)) result_str = cls.extract_result_str_from_response(response)
except json.JSONDecodeError: result = json.loads(result_str)
raise ValueError("failed to parse response") except json.JSONDecodeError as e:
raise ValueError(f"Failed to parse JSON response: {str(e)}. Response content: {result_str[:200]}...")
except ValueError as e:
# Re-raise ValueError from extract_result_str_from_response
raise e
except Exception as e:
raise ValueError(f"Unexpected error during response transformation: {str(e)}")
# Check if the result contains an error
if isinstance(result, dict) and "error" in result:
raise ValueError(f"JavaScript execution error: {result['error']}")
if not isinstance(result, dict): if not isinstance(result, dict):
raise ValueError("result must be a dict") raise ValueError(f"Result must be a dict, got {type(result).__name__}")
if not all(isinstance(k, str) for k in result): if not all(isinstance(k, str) for k in result):
raise ValueError("result keys must be strings") raise ValueError("Result keys must be strings")
return result return result
@classmethod @classmethod

Loading…
Cancel
Save