iOS原生通过WKWebView传JSON到JS时JSON.Parse报错求助
Hey there, let's troubleshoot that JSON.parse error you're hitting when passing data from WKWebView to JavaScript. I took a close look at the JSON snippet you shared, and there are a couple of clear syntax issues causing the problem—plus I'll show you the foolproof way to pass JSON between iOS and JS to avoid these headaches in the future.
First, let's address the broken syntax in your JSON:
- Extra closing brace in
postData: EachpostDatavalue has an extra}that breaks the JSON structure. For example:
Should be corrected to:// Your broken postData "{\"args\":[{\"Name\":\"ProcessName\",\"Value\":\"offlineformios\"},{\"Name\":\"isSubmitForm\",\"Value\":true}}]}"// Fixed postData "{\"args\":[{\"Name\":\"ProcessName\",\"Value\":\"offlineformios\"},{\"Name\":\"isSubmitForm\",\"Value\":true}]}" - Incomplete URLs: The
APIUrlfield is missing//(should be"https://some Url"instead of"https:some Url"), andCDNURL":...needs a complete, valid value (no ellipses allowed in valid JSON).
Manual JSON string concatenation is error-prone—use iOS's built-in JSONSerialization to generate valid JSON, then pass it safely to JavaScript. Here's how:
Step 1: Build your data structure in iOS
Start with native dictionaries/arrays to represent your config:
// Define user details let userDetails = [ "UserName": "Test User", "FullName": "", "EMailAddress": "" ] // Define a form data item (reuse for the second entry) let formDataItem = [ "postData": "{\"args\":[{\"Name\":\"ProcessName\",\"Value\":\"offlineformios\"},{\"Name\":\"isSubmitForm\",\"Value\":true}]}", "url": "https://Get Url", "type": "POST", "responseStatus": 200 ] // Assemble the full config dictionary let configDict = [ "config": [ "APIUrl": "https://some Url", "provider": "ActiveDirectory", "UserDetails": userDetails, "formdata": [formDataItem, formDataItem], "CDNURL": "https://your-actual-cdn-url.com" // Replace with real value ] ]
Step 2: Convert to a valid JSON string
Use JSONSerialization to ensure your string follows strict JSON rules:
do { let jsonData = try JSONSerialization.data(withJSONObject: configDict, options: []) guard let jsonString = String(data: jsonData, encoding: .utf8) else { print("Failed to convert JSON data to string") return } // Pass the valid JSON string to JS sendConfigToWebView(jsonString: jsonString) } catch { print("Error generating JSON: \(error.localizedDescription)") }
Step 3: Pass the JSON to JavaScript safely
Avoid manual string escaping by properly formatting the JS call. Here's how to send the string to a JS function:
func sendConfigToWebView(jsonString: String) { // Escape special characters for JavaScript compatibility let escapedJson = jsonString .replacingOccurrences(of: "\"", with: "\\\"") .replacingOccurrences(of: "\n", with: "\\n") // Call a JavaScript function to receive the config let jsCode = "window.handleAppConfig('\(escapedJson)');" webView.evaluateJavaScript(jsCode) { result, error in if let error = error { print("JS evaluation error: \(error.localizedDescription)") } } }
Step 4: Parse the JSON in your JavaScript
Add a function in your HTML/JS to receive and parse the data:
function handleAppConfig(jsonString) { try { const appConfig = JSON.parse(jsonString); console.log("Successfully loaded config:", appConfig); // Use your config data here } catch (error) { console.error("JSON Parse Error:", error); } }
The main issues were:
- Invalid JSON syntax: The extra
}inpostDatamade the entire JSON invalid, soJSON.parsecouldn't process it. - Manual string errors: Hand-building JSON strings often leads to missed escapes or syntax mistakes—using
JSONSerializationeliminates this risk.
内容的提问来源于stack exchange,提问作者Aneesh

