user2325154 user2325154 -4 years ago 128
JSON Question

How to get a value from JSON string in Swift using SwiftyJSON?

I have a

string and would like to obtain some values from it. I am using
to extract some values from the JSON string. But not sure why I am getting empty values from it. How can I retrieve all the values such as
version, ephemeralPublicKey, transactionId
etc from this JSON string using


let decryptedPaymentData:NSString! = NSString(data: encryptedPaymentData, encoding: NSUTF8StringEncoding)
print("decryptedPaymentData = \(decryptedPaymentData)")

//extract values here
let decryptedJsonStr = JSON(decryptedPaymentData)
let version = decryptedJsonStr["version"].stringValue
print("version = \(version)")


decryptedPaymentData = {"version":"EC_v1",

version =

Solution with Output:

let decryptedJsonStr = JSON.parse(decryptedPaymentData as String)
let version = decryptedJsonStr["version"].stringValue
let epk = decryptedJsonStr["header"]["ephemeralPublicKey"].stringValue
print("version = \(version)")
print("epk = \(epk)")

version = EC_v1

Answer Source

JSON(decryptedPaymentData) just constructs a JSON object which is a string "{\"version\":...}".

To parse it, you need to use the parse() function:

let decryptedJsonStr = JSON.parse(decryptedPaymentData)
//                          ^^^^^

Note that you don't need to convert the NSData into NSString yourself, as you could use the init(data:options:error:) constructor:

let decryptedJsonStr = JSON(data: encryptedPaymentData)
//                          ^^^^^
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download