Python导出JSON引号异常及js2py环境执行JS函数报错求助
Let’s fix your issue step by step—your main pain points were relying on unsupported ES6 template literals (backticks) and mishandling quote escaping when passing the JSON string to the js2py environment. Here’s a reliable, compatible approach:
Step 1: Define Your JS Function Normally
Keep your JavaScript function string intact in Python, with its original mix of single and double quotes—no premature replacements needed:
import json import js2py # Your original JS function with mixed quotes js_function = """ var convertDateTime = function (s, key, input) { console.log(' - Executing "convertDateTime".'); s[key] = input.dateTime.toISOString().split('Z')[0].replace('T', ' '); }; """ # Store the function in a Python dict as required f = {'function': js_function}
Step 2: Escape Quotes Safely for JS Parsing
When converting the Python dict to a JSON string, we need to ensure single quotes don’t break the JS JSON.parse() call (since we’re wrapping the JSON string in single quotes in JS). Instead of replacing quotes with backticks, escape single quotes with a backslash:
# Serialize the dict to JSON, then escape single quotes for JS compatibility spec = json.dumps(f).replace("'", "\\'")
This preserves the original JS syntax while ensuring the JSON string is valid when passed to the js2py environment.
Step 3: Execute in js2py
Now you can safely load the JSON into the js2py environment and evaluate the function without syntax errors:
# Initialize the js2py environment js_env = js2py.EvalJs() # Parse the JSON string into a JavaScript object js_env.execute("spec = JSON.parse('" + spec + "');") # Evaluate the function to make it available in the JS environment js_env.execute(spec['function']) # Test the function to confirm it works (example mock input) js_env.execute(""" var testResult = {}; var mockInput = {dateTime: new Date()}; convertDateTime(testResult, 'formattedDate', mockInput); console.log('Formatted date:', testResult.formattedDate); """)
Why Your Previous Approach Failed
- Replacing single quotes with backticks created ES6 template literals, which js2py’s default environment doesn’t support (causing the
NotImplementedError). - Removing escaped double quotes (
\\") corrupted the original JS string structure, leading to invalid JSON parsing.
Key Notes
- This method fully preserves your original JS function’s quote structure.
- Compatible with Python 2.7.13 and js2py’s non-ES6 environment.
- Works with any valid simple JS code that uses mixed single/double quotes.
内容的提问来源于stack exchange,提问作者F.Wessels

