ilker
ilker

Reputation: 67

How do I generate a filter string for JSON

Are there any conventions to generate a filter text for the objects I use in Swift ?

class Account {
  var active : Bool!
  ...
}

Example : I've Account class in Swift and Account model in loopback, I want to get the Accounts with field "active = true" the filter that I need to generate is = {"where" : {"active" : true}}

I type these kinds of queries by hand in need. I'm sure there's a way that someone thought about it, I just need the keyword.

PS: I extend my classes from Realm and ObjectMapper.

Upvotes: 1

Views: 737

Answers (1)

Eric Aya
Eric Aya

Reputation: 70111

Updated answer

If I understand your comment under my original answer, you need to generate a JSON String in the form of {"where" : {"active" : true}} where true is actually the bool value of your Account instance. This JSON String will then be used as a query/filter for MongoDB.

For this, I suggest you add a computed property to the Account class. This property will use NSJSONSerialization to create the JSON data from the bool, and use String() to create a JSON String from this data.

Example:

class Account {
    var active : Bool!

    var boolQuery: String? {
        let dict = ["where": ["active": active]]
        if let json = try? NSJSONSerialization.dataWithJSONObject(dict, options: []),
                query = String(data: json, encoding: NSUTF8StringEncoding) {
            return query
        }
        return nil
    }
}

Usage:

let acc = Account()
acc.active = true
if let query = acc.boolQuery {
    print(query)
}

Prints:

{"where":{"active":true}}

let acc = Account()
acc.active = false
if let query = acc.boolQuery {
    print(query)
}

Prints:

{"where":{"active":false}}

I'm not sure if I got the "who does what" in your setup (which class is reponsible for what), but it seems to me that it's the kind of code you needed.

It can also be a free function of course:

func boolQuery(account: Account) -> String? {
    let dict = ["where": ["active": account.active]]
    if let json = try? NSJSONSerialization.dataWithJSONObject(dict, options: []),
        query = String(data: json, encoding: NSUTF8StringEncoding) {
        return query
    }
    return nil
}

Etc.


Previous answer

It's a bit unclear from your question, and I'm not sure what you mean with "I type these kinds of queries by hand in need"... but I suppose that, anyway, you have an array of Account instances.

Then it's very easy to filter this array and get only the instances where active is true:

let result = arrayOfAccounts.filter { $0.active }

Here result is an array containing only the accounts where active is true.

Upvotes: 2

Related Questions