Skip to content

Instantly share code, notes, and snippets.

@santoshrajan
Created October 12, 2014 05:36
Show Gist options
  • Star 23 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save santoshrajan/97aa46871cde0c0cb8a8 to your computer and use it in GitHub Desktop.
Save santoshrajan/97aa46871cde0c0cb8a8 to your computer and use it in GitHub Desktop.
JSON Stringify in Swift
// Author - Santosh Rajan
import Foundation
let jsonObject: [AnyObject] = [
["name": "John", "age": 21],
["name": "Bob", "age": 35],
]
func JSONStringify(value: AnyObject, prettyPrinted: Bool = false) -> String {
var options = prettyPrinted ? NSJSONWritingOptions.PrettyPrinted : nil
if NSJSONSerialization.isValidJSONObject(value) {
if let data = NSJSONSerialization.dataWithJSONObject(value, options: options, error: nil) {
if let string = NSString(data: data, encoding: NSUTF8StringEncoding) {
return string
}
}
}
return ""
}
/*
* Usage
*/
let jsonString = JSONStringify(jsonObject)
println(jsonString)
// Prints - [{"age":21,"name":"John"},{"age":35,"name":"Bob"}]
/*
* Usage - Pretty Printed
*/
let jsonStringPretty = JSONStringify(jsonObject, prettyPrinted: true)
println(jsonStringPretty)
/* Prints the following -
[
{
"age" : 21,
"name" : "John"
},
{
"age" : 35,
"name" : "Bob"
}
]
*/
@tomasdev
Copy link

What about encoding strings? Like the answer at http://stackoverflow.com/questions/15843570/objective-c-how-to-convert-nsstring-to-escaped-json-string

So far, I have it working (but I don't like the repeating thing):

    func JSONString(var str: String) -> String {
        // \b = \u{8}
        // \f = \u{12}
        let insensitive = NSStringCompareOptions.CaseInsensitiveSearch
        str = str
            .stringByReplacingOccurrencesOfString("\"", withString: "\\\"", options: insensitive)
            .stringByReplacingOccurrencesOfString("/", withString: "\\/", options: insensitive)
            .stringByReplacingOccurrencesOfString("\n", withString: "\\n", options: insensitive)
            .stringByReplacingOccurrencesOfString("\u{8}", withString: "\\b", options: insensitive)
            .stringByReplacingOccurrencesOfString("\u{12}", withString: "\\f", options: insensitive)
            .stringByReplacingOccurrencesOfString("\r", withString: "\\r", options: insensitive)
            .stringByReplacingOccurrencesOfString("\t", withString: "\\t", options: insensitive)
        return str;
    }

BTW your posted stuff is not Swift 2 compatible :(

@ndyoussfi
Copy link

/* Changes: Works better this way!*/

func JSONStringify(value: AnyObject,prettyPrinted:Bool = false) -> String{

    let options = prettyPrinted ? NSJSONWritingOptions.PrettyPrinted : NSJSONWritingOptions(rawValue: 0)


    if NSJSONSerialization.isValidJSONObject(value) {

        do{
            let data = try NSJSONSerialization.dataWithJSONObject(value, options: options)
            if let string = NSString(data: data, encoding: NSUTF8StringEncoding) {
                return string as String
            }
        }catch {

            print("error")
            //Access error here
        }

    }
    return ""

}

@3lvis
Copy link

3lvis commented Apr 1, 2016

For debugging purposes it could be just this:

let data = try! NSJSONSerialization.dataWithJSONObject(JSON!, options: .PrettyPrinted)
let string = NSString(data: data, encoding: NSUTF8StringEncoding)
print(string)

@Edudjr
Copy link

Edudjr commented Feb 9, 2017

For debugging purposes it could be just this:

let data = try! NSJSONSerialization.dataWithJSONObject(JSON!, options: .PrettyPrinted)
let string = NSString(data: data, encoding: NSUTF8StringEncoding)
print(string)

update to Swift 3:

let data = try! JSONSerialization.data(withJSONObject: json, options: .prettyPrinted)
let string = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
print(string)

@SunLn
Copy link

SunLn commented Jul 19, 2017

swift 3.x update:

    func JSONStringify(value: AnyObject, prettyPrinted: Bool = true) -> String {
        let options = prettyPrinted ? JSONSerialization.WritingOptions.prettyPrinted : nil
        if JSONSerialization.isValidJSONObject(value) {
            do {
                let data = try JSONSerialization.data(withJSONObject: value, options: options!)
                if let string = NSString(data: data, encoding: String.Encoding.utf8.rawValue) {
                    return string as String
                }
            }  catch {
                return ""
            }
        }
        return ""
    }

@4l1k
Copy link

4l1k commented Sep 11, 2017

I like this version for Swift 3.x

`func JSONStringify(value: AnyObject, prettyPrinted: Bool = false) -> String {
        let options = prettyPrinted ? JSONSerialization.WritingOptions.prettyPrinted : nil
        
        if JSONSerialization.isValidJSONObject(value) {
            if let data = try? JSONSerialization.data(withJSONObject: value, options: options!) {
                
                if let string = NSString(data: data, encoding: String.Encoding.utf8.rawValue) {
                    return string as String
                }
            }
        }
        return ""
    }`

@ibrahimkteish
Copy link

ibrahimkteish commented Feb 13, 2018

Swift 4
I end up using this version

enum StringifyError: Error {
  case isNotValidJSONObject
}

struct JSONStringify {
  
  let value: Any
  
  func stringify(prettyPrinted: Bool = false) throws -> String {
    let options: JSONSerialization.WritingOptions = prettyPrinted ? .prettyPrinted : .init(rawValue: 0)
    if JSONSerialization.isValidJSONObject(self.value) {
      let data = try JSONSerialization.data(withJSONObject: self.value, options: options)
      if let string = String(data: data, encoding: .utf8) {
        return string
        
      }
    }
    throw StringifyError.isNotValidJSONObject
  }
}
protocol Stringifiable {
  func stringify(prettyPrinted: Bool) throws -> String
}

extension Stringifiable {
  func stringify(prettyPrinted: Bool = false) throws -> String {
    return try JSONStringify(value: self).stringify(prettyPrinted: prettyPrinted)
  }
}

extension Dictionary: Stringifiable {}
extension Array: Stringifiable {}

//Usage:
do {
 let stringified = try JSONStringify(value: ["name":"bob", "age":29]).stringify()
  print(stringified)
} catch let error { print(error) }

//Or
let dictionary = ["name":"bob", "age":29] as [String: Any]
let stringifiedDictionary = try dictionary.stringify()

let array = ["name","bob", "age",29] as [Any]
let stringifiedArray = try array.stringify()

print(stringifiedDictionary)
print(stringifiedArray)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment