Chris
Chris

Reputation: 431

How can I print this JSON value in Swift 5?

{
"optionChain": {
    "result": [
        {
            "underlyingSymbol": "AAPL",
            "expirationDates": [
                1606435200,
                1607040000,
                1607644800,
                1608249600,
                1608768000,
                1609372800,
                1610668800,
                1613692800,
                1616112000,
                1618531200,
                1623974400,
                1626393600,
                1631836800,
                1642723200,
                1655424000,
                1663286400,
                1674172800
            ],
            "strikes": [
                55,
                60,
                65,
                70,
                75
            ],
            "hasMiniOptions": false,
            

How can I print out "underlyingSymbol" or any of those related fields in JSON? I understand printing out a single JSON field, but how do I get into the embedded ones?

So I made the Decodable as Suggested below:

struct Something: Decodable
{
    let optionChain: OptionChain
    let error: String
}

struct OptionChain: Decodable
{
    let result: [ResultElement]
}

struct ResultElement: Decodable
{
    let underlyingSymbol: String
    let expirationDates: [Int]
    let strikes: [Int]
    let hasMiniOptions: Bool
    let quote: [quoteElement]
    let options: [optionsElement]
}

struct quoteElement: Decodable
{
    let language: String
    let region: String
    let quoteType: String
    let quoteSourceName: String
    let triggerable: Bool
    let currency: String
    let firstTradeDateMilliseconds: Int
    let priceHint: Int
    let regularMarketChange: Int
    let regularMarketChangePercent: Int
    let regularMarketTime: Int
    let regularMarketPrice: Int
    let regularMarketDayHigh: Int
    let regularMarketDayRange: String
    let regularMarketDayLow: Int
    let regularMarketVolume: Int
    let regularMarketPreviousClose: Int
    let bid: Int
    let ask: Int
    let bidSize: Int
    let askSize: Int
    let fullExchangeName: String
    let financialCurrency: String
    let regularMarketOpen: Int
    let averageDailyVolume3Month: Int
    let averageDailyVolume10Day: Int
    let fiftyTwoWeekLowChange: Int
    let fiftyTwoWeekLowChangePercent: Int
    let fiftyTwoWeekRange: String
    let fiftyTwoWeekHighChange: Int
    let fiftyTwoWeekHighChangePercent: Int
    let fiftyTwoWeekLow: Int
    let fiftyTwoWeekHigh: Int
    let dividendDate: Int
    let earningsTimestamp: Int
    let earningsTimestampStart: Int
    let earningsTimestampEnd: Int
    let trailingAnnualDividendRate: Int
    let trailingPE: Int
    let trailingAnnualDividendYield: Int
    let epsTrailingTwelveMonths: Int
    let epsForward: Int
    let epsCurrentYear: Int
    let priceEpsCurrentYear: Int
    let sharesOutstanding: Int
    let bookValue: Int
    let fiftyDayAverage: Int
    let fiftyDayAverageChange: Int
    let fiftyDayAverageChangePercent: Int
    let twoHundredDayAverage: Int
    let twoHundredDayAverageChange: Int
    let twoHundredDayAverageChangePercent: Int
    let marketCap: Int
    let forwardPE: Int
    let priceToBook: Int
    let sourceInterval: Int
    let exchangeDataDelayedBy: Int
    let tradeable: Bool
    let exchange: String
    let shortName: String
    let longName: String
    let marketState: String
    let messageBoardId: String
    let exchangeTimezoneName: String
    let exchangeTimezoneShortName: String
    let gmtOffSetMilliseconds: Int
    let market: String
    let esgPopulated: Bool
    let displayName: String
    let symbol: String
}

struct optionsElement: Decodable
{
    let expirationDate: Int
    let hasMiniOptions: Bool
    let calls: [callPutElement]
    let puts: [callPutElement]
}

struct callPutElement: Decodable
{
    let contractSymbol: String
    let strike: Int
    let currency: String
    let lastPrice: Int
    let change: Int
    let percentChange: Int
    let volume: Int
    let openInterest: Int
    let bid: Int
    let ask: Int
    let contractSize: String
    let expiration: Int
    let lastTradeDate: Int
    let impliedVolatility: Int
    let inTheMoney: Bool
}

However now I am receiving an error:

JSONSerialization error: dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "No string key for value in object around character 1." UserInfo={NSDebugDescription=No string key for value in object around character 1.})))

Upvotes: 1

Views: 581

Answers (1)

Rob C
Rob C

Reputation: 5073

I'd use the Codable apis:

struct Something: Decodable {
    let optionChain: OptionChain
}

struct OptionChain: Decodable {
    let result: [ResultElement]
}

struct ResultElement: Decodable {
    let underlyingSymbol: String
    let expirationDates: [Int]
    let strikes: [Int]
    let hasMiniOptions: Bool
}

let jsonString = "{...}"

let jsonData = jsonString.data(using: .utf8)!

let decoder = JSONDecoder()
let something = try decoder.decode(Something.self, from: jsonData)

print(something.optionChain.result.map { $0.underlyingSymbol })

Upvotes: 0

Related Questions