High performance JSONPath queries for Swift

Related tags

Database Sextant
Overview

Sextant

Sextant is a complete, high performance JSONPath implementation written in Swift. It was originally ported from SMJJSONPath, which in turn is a tight adaptation of the Jayway JsonPath implementation. Sextant has since been updated to bring it into compliance with other JSON path implementations (see issue), so this specific implementation now varies from the SMJJSONPath/Jayway implementation.

Overview

The original Stefan Goessner JsonPath implemenentation was released in 2007, and from it spawned dozens of different implementations. This JSONPath Comparison chart shows the wide array of available implemenations, and at the time of this writing a Swift implementation is not present (note that there exists the SwiftPath project, but it is not included in said chart due to critical errors when running on Linux.

Goals

  • Simple API
  • Full JSONPath implementation
  • High performance
  • Linux support

Usage

/// Each call to Sextant's query(values: ) will return an array on success and nil on failure
func testSimple0() {
    let json = #"["Hello","World"]"#
    guard let results = json.query(values: "$[0]") else { return XCTFail() }
    XCTAssertEqualAny(results[0], "Hello")
}
/// You can avoid the provided extensions and call query on the Sextant singleton directly
func testSimple1() {
    let json = #"["Hello","World"]"#
    guard let jsonData = json.data(using: .utf8) else { return }
    guard let jsonObject = try? JSONSerialization.jsonObject(with: jsonData, options: []) else { return }
    guard let results = Sextant.shared.query(jsonObject, values: "$[0]") else { return XCTFail() }
    XCTAssertEqualAny(results[0], "Hello")
}
/// Works with any existing JSON-like structure
func testSimple2() {
    let data = [ "Hello", "World" ]
    guard let results = data.query(values: "$[0]") else { return XCTFail() }
    XCTAssertEqualAny(results[0], "Hello")
}
/// Automatically covert to simple tuples
func testSimple3() {
    let json = #"{"name":"Rocco","age":42}"#
    
    guard let person: (name: String?, age: Int?) = json.query("$.['name','age']") else { return XCTFail() }
    XCTAssertEqual(person.name, "Rocco")
    XCTAssertEqual(person.age, 42)
}
/// Supports Decodable structs
func testSimple4() {
    let json = #"{"data":{"people":[{"name":"Rocco","age":42},{"name":"John","age":12},{"name":"Elizabeth","age":35},{"name":"Victoria","age":85}]}}"#
    
    class Person: Decodable {
        let name: String
        let age: Int
    }
    
    guard let persons: [Person] = json.query("$..[?(@.name)]") else { return XCTFail() }
    XCTAssertEqual(persons[0].name, "Rocco")
    XCTAssertEqual(persons[0].age, 42)
    XCTAssertEqual(persons[2].name, "Elizabeth")
    XCTAssertEqual(persons[2].age, 35)
}
/// Easily combine results from multiple queries
func testSimple5() {
    let json1 = #"{"error":"Error format 1"}"#
    let json2 = #"{"errors":[{"title:":"Error!","detail":"Error format 2"}]}"#
            
    let queries: [String] = [
        "$.error",
        "$.errors[0].detail",
    ]
    
    XCTAssertEqualAny(json1.query(string: queries), "Error format 1")
    XCTAssertEqualAny(json2.query(string: queries), "Error format 2")
}

Installation

Sextant is fully compatible with the Swift Package Manager

dependencies: [
    .package(url: "https://github.com/KittyMac/Sextant.git", .branch("main"))
],

License

Sextant is free software distributed under the terms of the MIT license, reproduced below. Sextant may be used for any purpose, including commercial purposes, at absolutely no cost. No paperwork, no royalties, no GNU-like "copyleft" restrictions. Just download and enjoy.

Copyright (c) 2021 Chimera Software, LLC

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

You might also like...
The Swift Package Index is the place to find Swift packages!
The Swift Package Index is the place to find Swift packages!

The Swift Package Index helps you make better decisions about the dependencies you use in your apps. The Swift Package Index is a search engine for pa

A stand-alone Swift wrapper around the mongo-c client library, enabling access to MongoDB servers.
A stand-alone Swift wrapper around the mongo-c client library, enabling access to MongoDB servers.

This package is deprecated in favour of the official Mongo Swift Driver. We advise users to switch to that pack

Elegant library to manage the interactions between view and model in Swift
Elegant library to manage the interactions between view and model in Swift

An assistant to manage the interactions between view and model ModelAssistant is a mediator between the view and model. This framework is tailored to

CRUD is an object-relational mapping (ORM) system for Swift 4+.

CRUD is an object-relational mapping (ORM) system for Swift 4+. CRUD takes Swift 4 Codable types and maps them to SQL database tables. CRUD can create tables based on Codable types and perform inserts and updates of objects in those tables. CRUD can also perform selects and joins of tables, all in a type-safe manner.

CoreXLSX is a Excel spreadsheet (XLSX) format parser written in pure Swift

CoreXLSX Excel spreadsheet (XLSX) format parser written in pure Swift CoreXLSX is a library focused on representing the low-level structure of the XML

Solutions to LeetCode by Swift
Solutions to LeetCode by Swift

LeetCode by Swift LeetCode Online Judge is a website containing many algorithm questions. Most of them are real interview questions of Google, Faceboo

Super lightweight DB written in Swift.
Super lightweight DB written in Swift.

Use of value types is recommended and we define standard values, simple structured data, application state and etc. as struct or enum. Pencil makes us store these values more easily.

YapDB is a collection/key/value store with a plugin architecture. It's built atop sqlite, for Swift & objective-c developers.
YapDB is a collection/key/value store with a plugin architecture. It's built atop sqlite, for Swift & objective-c developers.

YapDatabase is a collection/key/value store and so much more. It's built atop sqlite, for Swift & Objective-C developers, targeting macOS, iOS, tvOS &

CoreData/Realm sweet wrapper written in Swift
CoreData/Realm sweet wrapper written in Swift

What is SugarRecord? SugarRecord is a persistence wrapper designed to make working with persistence solutions like CoreData in a much easier way. Than

Comments
  • Is it possible to set value for jsonpaths

    Is it possible to set value for jsonpaths

    just as on com.jayway.jsonpath.DocumentContext.set(), are there any implementations for settings a value for given jsonpath ?

       /**
         * Set the value a the given path
         *
         * @param path      path to set
         * @param newValue  new value
         * @return a document context
         */
        DocumentContext set(JsonPath path, Object newValue);
    
    enhancement 
    opened by ilkerc 6
  • Cocoapods integration

    Cocoapods integration

    It would be great to utilize sextant as a cocoapods dependency inside a cocoapods framework. I did some search and looks like spm dependency never got implemented on cocoapods. To do that we should also add cocoapods support to Chronometer, Spanker and Hitch.

    Also; I still couldn't find a solution for running ios apps in simulator on an m1 based mac, without enabling rosetta in xCode (not a good idea). Could not find module ‘Sextant’ for target ‘x86_64-apple-ios-simulator’;

    What do you think @KittyMac ?

    enhancement good first issue 
    opened by ilkerc 2
Owner
Rocco Bowling
Rocco Bowling
Commands providing shortcuts to common Postgres introspection queries (Swift port of heroku-pg-extras)

Commands providing shortcuts to common Postgres introspection queries (Swift port of heroku-pg-extras)

Sven A. Schmidt 2 May 27, 2022
🔥 🔥 🔥Support for ORM operation,Customize the PQL syntax for quick queries,Support dynamic query,Secure thread protection mechanism,Support native operation,Support for XML configuration operations,Support compression, backup, porting MySQL, SQL Server operation,Support transaction operations.

?? ?? ??Support for ORM operation,Customize the PQL syntax for quick queries,Support dynamic query,Secure thread protection mechanism,Support native operation,Support for XML configuration operations,Support compression, backup, porting MySQL, SQL Server operation,Support transaction operations.

null 60 Dec 12, 2022
Sharing SQL queries between Server and Mobile databases

Sharing SQL queries between Server and Mobile databases Overview As we all know, code is expensive to maintain, and the more complex the code, the mor

Aaron LaBeau 4 May 24, 2022
A fast, pure swift MongoDB driver based on Swift NIO built for Server Side Swift

A fast, pure swift MongoDB driver based on Swift NIO built for Server Side Swift. It features a great API and a battle-tested core. Supporting both MongoDB in server and embedded environments.

null 646 Dec 10, 2022
SQLite.swift - A type-safe, Swift-language layer over SQLite3.

SQLite.swift provides compile-time confidence in SQL statement syntax and intent.

Stephen Celis 8.7k Jan 3, 2023
🧡 SQLiteOrm-Swift is an ORM library for SQLite3 built with Swift 5

?? Easy to use SQLite ORM library written with Swift

Yevgeniy Zakharov 25 Oct 6, 2022
ObjectBox Swift - persisting your Swift objects superfast and simple

ObjectBox Swift ObjectBox is a superfast, light-weight object persistence framework. This Swift API seamlessly persists objects on-device for iOS and

ObjectBox 380 Dec 19, 2022
Shows the issue with swift using an ObjC class which has a property from a swift package.

SwiftObjCSwiftTest Shows the issue with swift using an ObjC class which has a property from a swift package. The Swift class (created as @objc derived

Scott Little 0 Nov 8, 2021
Ios-App-ication-Swift - A simple iOS application made in Xcode using Swift

?? iPhone Calculator A simple iOS application made in Xcode using Swift. This ap

Kushal Shingote 1 Feb 2, 2022
Save-the-dot-project-swift - Save the dot project with swift

Save the Dot Apple introduced UIViewPropertyAnimator for iOS 10. We can use this

Kushal Shingote 2 Feb 8, 2022