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.


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)
            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)


Hacking with Swift is sponsored by Emerge

SPONSORED Why are Swift reference types bad for app startup time, and what’s the performance cost of protocol conformances? That’s just a couple of the topics you can learn about on the Emerge blog — written by the app performance experts behind Emerge’s advanced app optimization and monitoring tools, based on their experience of working at companies like Apple, Airbnb, Snap, and Spotify.

Find out more

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.