1

I'm new with Swift and am trying to get the JSON data from HTML I grabbed. I get the HTML from a website and there's one line in the whole result that has the data. Setup like: var obj = *JSON data*

How can I parse through the string results to only get that line and convert the data (right side of the equal sign) to JSON?

Here's my code to get the data (testURL is the url of the website):

if let url = testURL {
    do {
          let contents = try String(contentsOf: url)
          print(contents)
       } catch {
          // contents could not be loaded
       }
    } else {
       // the URL was bad!
 }
1
  • Where is the HTML code? Commented May 26, 2019 at 23:45

1 Answer 1

2

You can use this pod SwiftSoup to parse HTML

This block of code iterate over tags like script and get its attributes like src

if let url = testURL {
    do {
        let contents = try String(contentsOf: url)
        print(contents)
        do {
            let doc: Document = try SwiftSoup.parse(contents)
            for item in try doc.select("script") {
                let json = try item.attr("src")
                print(json)
            }
        } catch Exception.Error(let type, let message) {
            print(message)
        } catch {
            print("error")
        }
    } catch {
        // contents could not be loaded
    }
} else {
    // the URL was bad!
}

Replace script with json tag and src with attribute containing json

Don't forget to add import SwiftSoup

Hope you get the desired result.

Sign up to request clarification or add additional context in comments.

2 Comments

Hello, I added SwiftSoup and used your code, but when I replace "src" with the obj, which is the variable name that's pointed to the JSON, it just prints out the whole HTML received (from print(contents)). But the json variable does not print anything. What do you mean by JSON tag? I also looked through the docs before writing this and couldn't find/try anything that helped. What I want is inside a <script>. But the HTML result has multiple <script>s
Give me your html or URL to fetch html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.