NEW: Subscribe to Hacking with Swift+ and accelerate your learning! >>

Codable for parsing json with dynamic keys

Forums > Swift

Hi folks,

I'm 1 month into the world of Swift/SwiftUI coding and am building an app for fun that fetches stock data. Right now I'm trying to get the nested API results to conform to a codable model. I'm having trouble working with json where the first key is dynamic.

For example:

{
  "AAPL":{"quote":{},"chart":[]}, 
  "FB":{"quote":{},"chart":[]},
  "MSFT":{"quote":{},"chart":[]}
}

How would I structure my model to allow for the first key to be dynamic? Thanks for any help or pointers! I've been reading a lot of guides but they all seem to cover the basic cases where the keys are predictable and the most you need to do is convert to camelcase.

   

In cases such as this the way to go is mostly to implement the decoder yourself. https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types at the bottom is a small example

   

I got the dynamic key part working but now I need to figure out how to add a nested container to support the many quote {} properties:

https://gist.github.com/stammy/0872636a4c740e8a2011e57eaf09bbff

Still trying to learn the ins and outs of encode/decode.

   

Hacking with Swift is sponsored by Paw

SPONSORED Use Paw to build, test and describe web APIs. Paw has a lightning fast native macOS interface to compose requests, collaborate in real-time on API specs, and generate client code for your applications. You can import and export API definitions.

Discover Paw for Mac

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

Not logged in

Log in
 

Link copied to your pasteboard.