WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

How to ignore /n in decoded JSON data?

Forums > SwiftUI

Hey all, looking for some help here.

I'm downloaded JSON data from an API and there's a string in the data that randomly has /n in multiple spots. I tried created a function that using .replacingOccurrences to replace "/n" with " ". However sometimes the /n is in the middle of the word I'll end up with something like this: "This is an exam ple of what happens." where a random space happens in example. I tried created this function

 if text.contains("\n") {
            let newText = text.replacingOccurrences(of: "\n", with: "")
            return newText
        } else if text.contains("\n ") {
            let newText = text.replacingOccurrences(of: "\n ", with: " ")
            return newText

but it doesn't seem to work.

Any ideas?

   

Please post an example of the JSON you are dealing with. And preferably more of your code where you are decoding that JSON.

1      

Of course!

JSON example:

"flavor_text_entries": [
    {
      "flavor_text": "When several of\nthese POKéMON\ngather, their\felectricity could\nbuild and cause\nlightning storms.",
      "language": {
        "name": "en",
        "url": "https://pokeapi.co/api/v2/language/9/"
      },
      "version": {
        "name": "red",
        "url": "https://pokeapi.co/api/v2/version/1/"
      }

Full link: https://pokeapi.co/api/v2/pokemon-species/25/

func fetchSpecies(species: Species) async {
        guard let url = URL(string: species.url) else { fatalError("Missing URL") }
        let urlRequest = URLRequest(url: url)
        let dataTask = URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in
            if let error = error {
                print("request error:", error)
                return
            }
            guard let response = response as? HTTPURLResponse else { return }

            if response.statusCode == 200 {
                guard let data = data else { return }
                DispatchQueue.main.async {
                    do {
                        print("species pulled")
                        let decoder = JSONDecoder()
                        decoder.keyDecodingStrategy = .convertFromSnakeCase
                        let decodedSpeciesDetail = try decoder.decode(SpeciesDetail.self, from: data)
                        self.speciesDetail = decodedSpeciesDetail
                    } catch let error {
                        print("error decoding:", error)
                    }
                }
            }
        }
         dataTask.resume()
    }

   

Save 50% in my Black Friday sale.

SAVE 50% To celebrate WWDC22, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.