Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Returning some of a JSON array #124

Closed
sgoodwin opened this issue May 4, 2015 · 4 comments
Closed

Returning some of a JSON array #124

sgoodwin opened this issue May 4, 2015 · 4 comments

Comments

@sgoodwin
Copy link

sgoodwin commented May 4, 2015

Let's say the server returns a JSON array of photos. Each photo should have an ID, a URL, and maybe the name of the person who took it.

struct Photo {
   let id: String
   let authorName: String
   let URL: NSURL
}

Now, we don't wanna show a photo in the app if info is missing. A photo without the author's name breaks things, so I don't wanna mark it as optional. However, in it's current form, the decode function would return nil if one photo out of 20 were missing the name.

How complicated would it be to make decode return the 19 valid photos and maybe have information somewhere to say "this one photo was invalid" instead of showing 0 photos in the app when 19 are totally fine to show?

@gfontenot
Copy link
Collaborator

you could write your own parser to handle this. It would look a lot like the built in Array parser, but with catOptionals instead of sequence:

public func decodePartialArray<A where A: Decodable, A == A.DecodedType>(value: JSON) -> Decoded<[A]> {
  switch value {
  case let .Array(a): return catOptionals(A.decode <^> a)
  default: return .TypeMismatch("\(value) is not an Array")
  }
}

func catOptionals<T>(xs: [T?]) -> [T] {
    return xs.reduce([]) { accum, elem in
        return elem.map { accum + [$0] } ?? accum
    }
}

Then, in your decode function:

j <| "photos" >>- decodePartialArray

@tonyd256
Copy link
Contributor

tonyd256 commented May 4, 2015

Yes, it's doable, but you might want to look into why you have partial information about a photo. If it's just because you're dealing with bad data that you don't have control over then that's one thing but if you do control that then fixing the data source to return full or no data for an image might be easier and more reliable.

@gfontenot
Copy link
Collaborator

You'll need to wrap that successful return statement in pure, too.

@sgoodwin
Copy link
Author

sgoodwin commented May 5, 2015

Ah yes, that would work.

Tony: In this one case I have control over the API, but on most client projects I don't so I was curious.

Thanks again!

@sgoodwin sgoodwin closed this as completed May 5, 2015
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants