user3069232 user3069232 -4 years ago 72
Swift Question

Using SwiftyJSON package

Trying to use SwiftyJSON library, but struggling for a day or so now.

I got this JSON.


I read it in from a file and assign it like this?

let quickfix = String(data: response.1, encoding: String.Encoding.utf8)
let json2F = JSON(quickfix!)

It seems to work. I can print this.


But I can do next to nothing beyond that. It hasn't parsed seems, I think it is just a string.

I am unable to figure out how to access the data within it. I also tried this...

if let dataFromString = quickfix?.data(using: .utf8, allowLossyConversion: false) {
let json2E = JSON(data: dataFromString)
print("json2E debugDescription \(json2F.debugDescription)")

But it returns null!! How to use this library?

Answer Source

You code looks good to me. It seems that your JSON is not valid.

Try to put an encapsulating object {} around it. Like this:

{"blah": [{"xdeltaY":0, "xdeltaX":0, "blah1":435, "blah2":"\/Numbers\/Numbers.001.png", "height":693.2142857142857, "width":1200, "blah3":240}]}

And additionally make sure you are using the right "not .


I also like to share a extension I use for getting my JSON from a string, which also gives you error messages in the console logs to prevent invalid JSON to mess up your program.

import Foundation
import SwiftyJSON

public extension String {
    public func toJSON() -> JSON? {
        if let data = String.Encoding.utf8, allowLossyConversion: false) {
            var jsonError: NSError?
            let json = JSON(data: data, error: &jsonError)
            if jsonError == nil {
                return json
            } else {
        return nil

    public func toJSONValue() -> JSON {
        return self.toJSON() ?? JSON.null
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download