0

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?

2
  • your inner elements appear to be in (an approximation to) JSON format - the Apple libraries include functions for decoding those. Commented May 11, 2019 at 6:46
  • Shouldn’t we expect to see some effort from OP, some code that shows that some effort was made to solve this? Commented May 11, 2019 at 7:19

1 Answer 1

1

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
}
Sign up to request clarification or add additional context in comments.

2 Comments

thanks this will work for transaction id only how i print same for pin and serial?? @vadian
Actually just add a loop but this way doesn't work for the serial value because it doesn't fit in an Int64.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.