You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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.

1. Fix the Invalid JSON in Your Original Content

First, let's address the broken syntax in your JSON:

  • Extra closing brace in postData: Each postData value has an extra } that breaks the JSON structure. For example:
    // Your broken postData
    "{\"args\":[{\"Name\":\"ProcessName\",\"Value\":\"offlineformios\"},{\"Name\":\"isSubmitForm\",\"Value\":true}}]}"
    
    Should be corrected to:
    // Fixed postData
    "{\"args\":[{\"Name\":\"ProcessName\",\"Value\":\"offlineformios\"},{\"Name\":\"isSubmitForm\",\"Value\":true}]}"
    
  • Incomplete URLs: The APIUrl field is missing // (should be "https://some Url" instead of "https:some Url"), and CDNURL":... needs a complete, valid value (no ellipses allowed in valid JSON).
2. The Correct Way to Pass JSON from iOS to JavaScript

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);
    }
}
3. Why Your Original Code Broke

The main issues were:

  • Invalid JSON syntax: The extra } in postData made the entire JSON invalid, so JSON.parse couldn't process it.
  • Manual string errors: Hand-building JSON strings often leads to missed escapes or syntax mistakes—using JSONSerialization eliminates this risk.

内容的提问来源于stack exchange,提问作者Aneesh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:17:04