简体   繁体   中英

Parse HTML string into JSON in swift

I am working with javascript to display string using HTML to WKWebView

Call Javascript function in my View Controller

myWebView.evaluateJavaScript("customMessageWithDictionary('\(self.jsonString)','\(strTestType)')") {
            (id, error) in
            print(error ?? "")
        }

In HTML file

function customMessageWithDictionary(nameDetails,testType1) {

        nameDetails = nameDetails.replace(/\\/g, '');
        questionList = $.parseJSON(nameDetails);
        var iterator=0
        for (iterator = 0; iterator < questionList.length; iterator++)
            questionList[iterator].UserGivenAnswerId= null;

        questionObj = questionList[positionObj];
        testType=testType1;

        loadQuestions(true);
    }

If there is an HTML Tags in jsonString so fetch the error and my Javascript not run. So WKWebview is not displaying the content.

Give me the solution if HTML tag is in my jsonString so load javascript function using HTML string.

 if let theJSONData = try?  JSONSerialization.data( withJSONObject: self.aryOfQuestionList,options: .prettyPrinted ),

let theJSONText = String(data: theJSONData,encoding: String.Encoding.ascii) 
{
   print("JSON string = \n\(theJSONText)")

   self.jsonString = (theJSONText as AnyObject) as! String
}

let regex = try! NSRegularExpression(pattern: "(?<=<\\w{1,40})\\s[^>]+(?=>)", options: .caseInsensitive)
let range = NSMakeRange(0, self.jsonString.count)
let htmlWithoutInlineAttributes = regex.stringByReplacingMatches(in: self.jsonString, options: [], range: range, withTemplate: "")

 print(htmlWithoutInlineAttributes)

To retrieve URLs for application resources, you should use URLForResource method of NSBundle class.

Swift 2

let url = NSBundle.mainBundle().URLForResource("privacy", withExtension:"html") 

Swift 3

let url = Bundle.main.url(forResource: "privacy", withExtension: "html")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM