Dhara
Dhara

Reputation: 35

Get specific value from Array Object in swift

i want to get value of transaction id from this array.

Here is my array::

["{
transaction_id:1894934,
 pin:0534552925794805, 
serial:20236031783146920986
}",
 "{transaction_id:1894935,
 pin:0665208961850777,
 serial:20236031783146920987}"]

How can i get value of transaction id from this ?? It seems like objects in array and my values are stored in this format so, how can i retrieve particular value?

Upvotes: 0

Views: 820

Answers (1)

vadian
vadian

Reputation: 285079

That's a pretty extraordinary format, an array of pseudo JSON strings. Pseudo, because they are not valid, the keys must be wrapped in double quotes.

A possible solution is to extract the values for transaction_id with Scanner

let array = ["{transaction_id:1894934,pin:0534552925794805,serial:20236031783146920986}","{transaction_id:1894935,pin:0665208961850777,serial:20236031783146920987}"]

let identifiers = array.compactMap{ string -> Int? in
    let scanner = Scanner(string: string)
    var value = 0
    guard scanner.scanCharacters(from: CharacterSet.decimalDigits.inverted, into: nil),
        scanner.scanInt(&value) else { return nil }
    return value
}

print(identifiers)

To convert the string into a dictionary use Regular Expression

let transactions = array.map{ string -> [String:String] in
    let regex = try! NSRegularExpression(pattern: "(\\w+):(\\d+)")
    var result = [String:String]()
    let matches = regex.matches(in: string, range: NSRange(string.startIndex..., in: string))
    for match in matches {
        let keyRange = Range(match.range(at: 1), in: string)!
        let valueRange = Range(match.range(at: 2), in: string)!
        result[String(string[keyRange])] = String(string[valueRange])
    }
    return result
}

Upvotes: 1

Related Questions