• Stars
    star
    116
  • Rank 293,133 (Top 6 %)
  • Language
    Swift
  • License
    MIT License
  • Created about 8 years ago
  • Updated over 5 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

⚗️ Functional JSON Parser - Linux Ready 🐧

Alembic

Functional JSON Parser


Swift4 Build Status CodeBeat


CocoaPods Carthage Swift Package Manager


Platform Lincense


Feature

  • Linux Ready
  • Type-safe JSON parsing
  • Functional value transformation
  • Easy to parse nested value
  • Dependency free
  • No defined custom operators

Requirements

  • Swift4.1 or later
  • OS X 10.9 or later
  • iOS 9.0 or later
  • watchOS 2.0 or later
  • tvOS 9.0 or later
  • Linux

Installation

Add the following to your Podfile:

use_frameworks!

target 'TargetName' do
  pod 'Alembic'
end

Add the following to your Cartfile:

github "ra1028/Alembic"

Add the following to your Package.swift:

// swift-tools-version:4.0

let package = Package(
    name: "ProjectName",
    dependencies : [
        .package(url: "https://github.com/ra1028/Alembic.git", .upToNextMajor(from: "3"))
    ]
)

Example

In example, parse the following JSON:

{
    "teams": [
        {
            "name": "Team ra1028",
            "url": "https://github.com/ra1028",
            "members": [
                {
                    "name": "Ryo Aoyama",
                    "age": 23
                },
                {
                    "name": "John Doe",
                    "age": 30
                }
            ]
        }
    ]
}

Make the JSON instance from Any, Data or String type JSON object.

// from `Any` type JSON object
let json = JSON(object)
// from JSON Data
let json = try JSON(data: data)
// from JSON String
let json = try JSON(string: string)

Parse value from JSON:

Parse the values type-safely

let memberName: String = try json.value(for: ["teams", 0, "members", 0, "name"])

Parse nullable value

let missingText: String? = try json.option(for: "missingKey")

Parse value from JSON with transforming:

Transform value using various monadic functions.

let teamUrl: URL = try json.parse(String.self, for: ["teams", 0, "url"])
        .filterMap(URL.init(string:))
        .value()

Transform nullable value if exist

let missingUrl: URL? = try json.parse(String.self, for: "missingKey")
        .filterMap(URL.init(string:))
        .option()

Mapping to model from JSON:

All types conforming to Parsable protocol and it's Array, Dictionary can be parsed.

struct Member: Parsable {
    let name: String
    let age: Int

    static func value(from json: JSON) throws -> Member {
        return try .init(
            name: json.value(for: "name"),
            age: json.value(for: "age")
        )
    }
}

extension URL: Parsable {
    public static func value(from json: JSON) throws -> URL {
        guard let url = try URL(string: json.value()) else {
            throw JSON.Error.dataCorrupted(value: json.rawValue, description: "The value was not valid url string.")
        }
        return url
    }
}

struct Team: Parsable {
    let name: String
    let url: URL
    let members: [Member]

    static func value(from json: JSON) throws -> Team {
        return try .init(
            name: json.value(for: "name"),
            url: json.value(for: "url"),
            members: json.value(for: "members")
        )
    }
}
let team: Team = try json.value(for: ["teams", 0])

Tips

The types conformed to Parsable as default.

JSON
String
Int
UInt
Double
Float
Bool
NSNumber
Int8
UInt8
Int16
UInt16
Int32
UInt32
Int64
UInt64
Decimal
Array where Element: Parsable
Dictionary where Key == String, Value: Parsable
Optional where Wrapped: Parsable

Conform to Parsable with initializer

struct Member: ParseInitializable {
    let name: String
    let age: Int

    init(with json: JSON) throws {
        name = try json.value(for: "name")
        age = try json.value(for: "age")
    }
}

Usage Reference Files

Functional operators for value transforming:

Errors

More Example

See the Test files


Playground

  1. Open Alembic.xcworkspace.
  2. Build the Alembic for Mac.
  3. Open Alembic playground in project navigator.

Contribution

Welcome to fork and submit pull requests!

Before submitting pull request, please ensure you have passed the included tests. If your pull request including new function, please write test cases for it.


License

Alembic is released under the MIT License.


More Repositories

1

DifferenceKit

💻 A fast and flexible O(n) difference algorithm framework for Swift collection.
Swift
3,421
star
2

RACollectionViewReorderableTripletLayout

The custom collectionView layout that can perform reordering of cells by dragging it.
Objective-C
1,481
star
3

Former

Former is a fully customizable Swift library for easy creating UITableView based form.
Swift
1,307
star
4

Carbon

🚴 A declarative library for building component-based user interfaces in UITableView and UICollectionView.
Swift
1,291
star
5

RAReorderableLayout

A UICollectionView layout whitch can move item with drag and drop.
Swift
867
star
6

DiffableDataSources

💾 A library for backporting UITableView/UICollectionViewDiffableDataSource.
Swift
836
star
7

swiftui-hooks

🪝 A SwiftUI implementation of React Hooks. Enhances reusability of stateful logic and gives state and lifecycle to function view.
Swift
479
star
8

SwiftUI-Combine

This is an example project of SwiftUI and Combine using GitHub API.
Swift
452
star
9

VueFlux

♻️ Unidirectional State Management Architecture for Swift - Inspired by Vuex and Flux
Swift
331
star
10

PathDynamicModal

A modal view using UIDynamicAnimator, like the Path for iOS.
Swift
286
star
11

swiftui-atom-properties

⚛️ Atomic approach state management and dependency injection for SwiftUI
Swift
232
star
12

FloatingActionSheetController

FloatingActionSheetController is a cool design ActionSheetController library written in Swift2.
Swift
140
star
13

DelegateProxy

Proxy for receive delegate events more practically
Swift
129
star
14

RASlideInViewController

RASlideInViewController has an transition effect expressing the depth, and you can dismiss it by draging
Objective-C
127
star
15

swift-mod

A tool for Swift code modification intermediating between code generation and formatting.
Swift
100
star
16

SwiftUI-Flux

🚀 This is a tiny experimental application using SwiftUI with Flux architecture.
Swift
54
star
17

monkey-lang-swift

The Monkey Programming Language written in Swift -- Writing An Interpreter In Go
Swift
17
star
18

LiveStreamingApp

A sample app repository that broadcasting and player of HLS for iOS.
Swift
16
star
19

KenBurnsSlideshowView

Slideshow with Ken Burns effect for iOS.
Swift
11
star
20

VueFluxExample-GitHub

VueFlux VueFluxReactive example project
Swift
8
star
21

OwnKit

My own utility toolkit for ios
Swift
7
star
22

ra1028

2
star
23

Dribbble_client_sample

Swift
1
star