0

I have a JSON array var array: [JSON] = [] that I would like to cast as a 'regular' array so that I can perform some filtering and other data manipulation. What would be the suggested approach to do so?

I've tried let filteredArray = array.arrayValue.filter {$0["submission_id"] as! Int == 27} but I was thrown this error

Value of type '[JSON]' has no member 'arrayValue'

8
  • What library are you using to parse the JSON? Commented Jun 2, 2016 at 5:14
  • I'm using swiftyjson and alamofire Commented Jun 2, 2016 at 5:14
  • If the type is [JSON] then that is already a "regular array". array.filter should work. Commented Jun 2, 2016 at 5:15
  • I've tried that too but I would get a Cast from 'JSON' to unrelated type 'Int' always fails Commented Jun 2, 2016 at 5:17
  • 1
    $0["submission_id"].double should give you a double, that's close ... Commented Jun 2, 2016 at 5:20

1 Answer 1

2

A SwiftyJSON object has an index and content.

To filter a SwiftyJSON object, you can use filter but you have to filter on the second part of the tuple, the content.

Also, you should use the .int property generated by SwiftyJSON if you want to get the Int value.

Example:

let filtered = json.filter { $0.1["submission_id"].int == 27 }

But you can also extract the contents of the SwiftyJSON object to get a Swift array, with .arrayObject.

Then you would filter like this:

if let array = json.arrayObject {
    let filtered = array.filter { $0["submission_id"] as? Int == 27 }
}
Sign up to request clarification or add additional context in comments.

Comments

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.