如何处理Python requests获取的带callback前缀的JSONP格式响应以单独访问各字段值
Got it, this is a super common issue when dealing with JSONP responses (that's what this callback(...) format is called)! Let's break down how to strip that wrapper and get access to the actual data fields easily.
Step 1: Extract the raw JSON string from the response
The response is wrapped in callback(...), so we first need to strip off that outer layer. There are two reliable ways to do this:
Option 1: Simple string replacement (good if you know the wrapper is exactly callback( and ))
response_text = 'callback({"Abn":"123", "AbnStatus":"Active", "AbnStatusEffectiveFrom":"2020-12-12", "Acn":"", "AddressDate":"2020-02-04", "AddressPostcode":"1111", "AddressState":"CTG", "BusinessName":[], "EntityName":"SOME NAME", "EntityTypeCode":"CPP", "EntityTypeName":"SOME SECTOR", "Gst":"2000-07-01", "Message":""})' # Strip the wrapper json_str = response_text.replace('callback(', '').rstrip(')')
Option 2: Index-based extraction (more robust for edge cases)
If there's any chance of whitespace or slight variations in the wrapper, use string indexing to find the start and end of the JSON content:
start_idx = response_text.find('(') + 1 end_idx = response_text.rfind(')') json_str = response_text[start_idx:end_idx]
Step 2: Parse the JSON string into a Python dictionary
Once you have the clean JSON string, use Python's built-in json module to convert it into a dictionary you can work with:
import json data = json.loads(json_str)
Step 3: Access your desired fields
Now you can access any field by its key, just like a regular Python dictionary:
# Get the ABN number abn = data['Abn'] # Returns "123" # Get the ABN status abn_status = data['AbnStatus'] # Returns "Active" # Example: Print the entity name print(f"Entity Name: {data['EntityName']}")
Bonus: Add error handling
To make your code more resilient (in case the response format is unexpected), wrap the parsing in a try-except block:
import json response_text = 'callback({"Abn":"123", ...})' try: start_idx = response_text.find('(') + 1 end_idx = response_text.rfind(')') json_str = response_text[start_idx:end_idx] data = json.loads(json_str) # Access fields safely abn = data.get('Abn', 'N/A') # Use get() to avoid KeyError if field is missing abn_status = data.get('AbnStatus', 'N/A') print(f"ABN: {abn}") print(f"Status: {abn_status}") except (ValueError, IndexError) as e: print(f"Failed to parse response: {str(e)}")
内容的提问来源于stack exchange,提问作者Saadi Mohammed

