如何将变量字符串嵌入JSON payload?拼接失败求助
Hey there! It looks like you're working on embedding variable values into a JSON payload (probably for a Jira API call, given those field names). The main issue with your current attempt is that you're putting variable names like "summary":"s" as literal strings instead of inserting the actual values of your variables. Let's fix this with two approaches, starting with the most reliable one:
json.dumps (Highly Recommended) Building JSON by hand with string concatenation is error-prone—you'll run into issues with quote escaping, special characters, and formatting. Instead, create a Python dictionary with your variables, then convert it to a valid JSON string automatically.
First, confirm your variables are correctly assigned (assuming issues is already parsed from JSON):
r = issues["fields"]["resolution"]["name"] p = issues["fields"]["customfield_13709"] s = issues["fields"]["summary"] k = issues["key"] a = issues["fields"]["assignee"]["name"]
Then build your payload as a dictionary, directly inserting the variables:
import json # Define the payload structure as a Python dict payload_data = { "fields": { "project": {"key": "SSETOPS"}, "summary": s, # Insert your summary variable here "description": f"{k} + {s}", # Use an f-string to concatenate k and s "issuetype": {"name": "Bug"} # Fill in your actual issue type name here # Add other fields if needed, e.g.: # "assignee": {"name": a}, # "resolution": {"name": r} } } # Convert the dict to a properly formatted JSON string payload = json.dumps(payload_data, indent=2) # Indent makes it human-readable
This method handles all quote escaping and formatting for you—no more messy manual string building!
If you absolutely need to build the string manually, you'll need to use string formatting to insert your variable values instead of writing them as literal strings. Use f-strings for clean syntax:
payload = f'''{{ "fields": {{ "project": {{"key": "SSETOPS"}}, "summary": "{s}", "description": "{k} + {s}", "issuetype": {{"name": "Bug"}} }} }}'''
⚠️ Warning: This will break if your variables (s, k, etc.) contain special characters like double quotes or backslashes. Stick with the dictionary method to avoid these headaches.
The core mistake in your original code was that "summary":"s" uses the literal string "s" instead of referencing your s variable. By inserting the variable directly (in the dict method) or using f-strings (in the manual method), you'll get the actual values into your payload.
内容的提问来源于stack exchange,提问作者user3254437

