Parsing JSON in Swift with Freddy


I’m trying to implement Freddy, the new Open-Source Framework for Parsing JSON in Swift provided by the BNR. I like the neat syntax and the use of optionals.
However, I’m stuck in this case :

This is a JSON that gives stock quotes, provided by Yahoo YQL :

{ "query": { "count": 2, "created": "2013-12-15T12:28:26Z", "lang": "en-US", "diagnostics": { "publiclyCallable": "true", "url": { "execution-start-time": "0", "execution-stop-time": "2", "execution-time": "2", "content": "" }, "user-time": "4", "service-time": "2", "build-version": "0.2.2090" }, "results": { "row": [ { "symbol": "EURUSD=X", "price": "1.3739", "date": "12/14/2013", "time": "7:20am", "changeValue": "N/A", "changePercentage": "N/A" }, { "symbol": "AAPL", "price": "554.43", "date": "12/13/2013", "time": "4:00pm", "changeValue": "-6.11", "changePercentage": "-1.09%" } ] } } }

My issue is : in the “results” dictionary, “row” is either a dictionary (if there is only one entry to fetch stocks quotes for) or an array of dictionaries (as in this case, if there are more than one entry).
How can I manage both cases with the same code?

I tried the following code, but it does not work, because in the first case, the “getStockInfoFromJSONDictionary” helper function is expecting a [String : JSON] dictionary, and in the other case, it is expecting an array.

[code] // The format of the JSON file changes whether the “count” property is 1 or more
let count = try“query”, “count”)

        if count == 0 {
            print("Array of stocks is empty")
        } else if count == 1 {
            // If there is only 1 stock, "row" is a dictionary
            let row = try json.dictionary("query", "results", "row")
            try getStockInfoFromJSONDictionary(row)
        } else if count > 1 {
            // If there is more than 1 stock, "row" is an array of dictionaries
            let row = try json.array("query", "results").map { try ($0.dictionary("row")) }
            for quote in row {
                try getStockInfoFromJSONDictionary(quote)

func getStockInfoFromJSONDictionary(dictionary: [String : JSON]) throws { … }


Any help will be much appreciated.


I found this solution :

if let symbol = dict["symbol"] { let code = String(symbol) }

I’m not particularly found of it because it uses the usual dictionary subscripting, but at least it works.

The other set of ideas that are not the same.