Swiftpack.co - nchlscs/swift-json as Swift Package

Swiftpack.co is a collection of thousands of indexed Swift packages. Search packages.
See all packages published by nchlscs.
nchlscs/swift-json 0.3.0
Handle JSON in Swift dynamically
⭐️ 0
🕓 1 year ago
.package(url: "https://github.com/nchlscs/swift-json.git", from: "0.3.0")

Swift JSON

swift-json is a dynamic wrapper around JSON decoders that uses @dynamicMemberLookup and @dynamicCallable features to access values from JSON data.

Overview

This is useful for accessing specific values from JSON data when you want to skip over unwanted boilerplate abstractions. For instance, we have the following fragment, and the longitude value is all we are interested in:

let data = """
  {
    "address": {
      "city": "Stockholm",
      "geo": {
        "latitude": 59.2,
        "longitude": 18.04
      }
    }
  }
  """
  .data(using: .utf8)!

To achieve this with JSONDecoder, we need to populate the following structs:

import Foundation

struct Response: Decodable {
  let address: Address
}

struct Address: Decodable {
  let geo: Geo
}

struct Geo: Decodable {
  let longitude: Double
}

let longitude = try JSONDecoder()
  .decode(Response.self, from: data)
  .address
  .geo
  .longitude

// Prints 18.04
print(longitude)

With swift-json it would be:

import JSON

let longitude: Double = try JSON(data)
  .address
  .geo
  .longitude

// Prints 18.04
print(longitude)

More examples

See tests

Installation

Swift Package Manager

.package(url: "https://github.com/nchlscs/swift-json", from: "0.3.0")

GitHub

link
Stars: 0
Last commit: 51 weeks ago
Advertisement: IndiePitcher.com - Cold Email Software for Startups

Swiftpack is being maintained by Petr Pavlik | @ptrpavlik | @swiftpackco | API | Analytics