-3

My requirement is to create a JSON from the text entered in a UITextField. There is no restriction to the UITextField. So, if a user enters a special character(", \ etc.), I want to escape the value entered and create a JSON.

String literals can include the following special characters:

  • The escaped special characters \0 (null character), \ (backslash), \t (horizontal tab), \n (line feed), \r (carriage return), \" (double quote) and \' (single quote)
  • An arbitrary Unicode scalar, written as \u{n}, where n is a 1–8 digit hexadecimal number with a value equal to a valid Unicode code point

For example, if the user enters "Hello "User"! How to use a \ in a JSON?". It should return something like this "Hello \"User\"! How to use a \\ in a JSON?". Not just " or \, I would want to escape all the special characters.

Thanks! I truly appreciate your effort in providing me with a solution.

Edit I forgot to mention, this requirement is for Swift 4.2.

avrospirit
  • 173
  • 4
  • 15
  • What have you tried? In what context do you want to achieve this? Having `struct Data { var input : String }` and then https://stackoverflow.com/questions/29599005/how-to-serialize-or-convert-swift-objects-to-json should be fine. – luk2302 May 10 '19 at 14:32

1 Answers1

2

Do not “manually” escape the characters in order to create JSON. There is a dedicated JSONEncoder() class for this purpose.

Top-level JSON objects can only be arrays or dictionaries. Here is an example for an array containing a single element with the given string:

let text = """
    Hello "User"! How to use a \\ in a JSON?
    Another line line
    """

do {
    let jsonData = try JSONEncoder().encode([text])
    let jsonString = String(data: jsonData, encoding: .utf8)!
    print(jsonString)
} catch {
    print(error.localizedDescription)
}

The output is

["Hello \"User\"! How to use a \\ in a JSON?\nAnother line"]
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • Have you tried this? This does not work -> `let valueString = #"{"value": "testing a \ and a " also an & with { value }"}"# print(valueString) do { let jsonData = try JSONEncoder().encode(valueString) let jsonString = String(data: jsonData, encoding: .utf8)! print(jsonString) } catch { print(error.localizedDescription) }` – avrospirit May 10 '19 at 15:15
  • @avrospirit: As I said, you have to embed the string in an array or dictionary: `JSONEncoder().encode([valueString])` – Martin R May 10 '19 at 15:17
  • He's not using Swift 5, so example might want to remove `#` and use `\\`. – matt May 10 '19 at 15:22
  • @avrospirit: I have “downgraded” the code for Swift 4.2. Please let me know if there are still problems. – Martin R May 10 '19 at 17:43
  • Thanks @MartinR. I missed the embedding part in the string. – avrospirit May 10 '19 at 22:09