Parse JSON like a badass

Related tags

JSON SwiftJSONParser
Overview

Parse JSON like a badass

Full disclaimer regarding performance

For production apps (or if you care about efficiency at all), I highly recommend using SwiftyJSON over this library. After benchmarking, I found that SwiftJSONParser could be up to 7x slower than SwiftyJSON.

This sucks

let jsonData = NSData(contentsOfURL: NSURL(string: url))
var jsonErrorOptional: NSError?
let jsonOptional: AnyObject! = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions(0), error: &jsonErrorOptional)

if let json = jsonOptional as? Dictionary<String, AnyObject> {
    if let other = json["other"] as? Dictionary<String, AnyObject> {
        if let nicknames = other["nicknames"] as? Array<String> {
            if let handle = nicknames[0] as AnyObject? as? String {
                println("Some folks call me \(handle)")
            }
        }
    }
}

This is readable

let jsonData = NSData(contentsOfURL: NSURL(string: url))
let parser = JSONParser(jsonData)

if let handle = parser.getString("other.nicknames[0]") {
    println("Some folks call me \(handle)")
}

Usage

Sample JSON payload we want to parse

{
    "name": "Mike",
    "favorite_number": 19,
    "gpa": 2.6,
    "favorite_things": ["Github", 42, 98.6],
    "other": {
        "city": "San Francisco",
        "commit_count": 9000,
        "nicknames": ["mrap", "Mikee"]
    }
}

Get values of a specific type. Returns optionals

if let name = parser.getString("name") {
    println("My name is \(name)")
}

if let number = parser.getInt("favorite_number") {
    println("\(number) is my favorite number!")
}

if let gpa = parser.getDouble("gpa") {
    println("My stellar highschool gpa was \(gpa)")
}

Or get AnyObject if you're not sure

if let city = parser.get("other.city") {
    // city will be type AnyObject
}

Get an Array of values

if let favorites = parser.getArray("favorite_things") {
    // favorites => ["Github", 42, 98.6]
}

Error Handling

If you're not sure about incoming json data, check it first

let badJsonData = NSData(contentsOfURL: NSURL(string: url))
let parser = JSONParser(badJsonData)

// Check for an error
if parser.error != nil {
   // Do stuff with json
} else {
   // Handle the error
   println(parser.error)
}

Installation

The best way to use SwiftJSONParser is to import it as a framework.

  1. Clone a local copy of SwiftJSONParser in any directory you'd like. git clone [email protected]:mrap/SwiftJSONParser.git

  2. Drag SwiftJSONParser.xcodeproj into your project's project navigator

  3. Add SwiftJSONParser as a Target Dependency.

  • Go to your App Target > Build Phases
  • In Target Dependencies, press +, select SwiftJSONParser
You might also like...
Reflection based (Dictionary, CKRecord, NSManagedObject, Realm, JSON and XML) object mapping with extensions for Alamofire and Moya with RxSwift or ReactiveSwift

EVReflection General information At this moment the master branch is tested with Swift 4.2 and 5.0 beta If you want to continue using EVReflection in

Freddy - A reusable framework for parsing JSON in Swift.
Freddy - A reusable framework for parsing JSON in Swift.

Why Freddy? Parsing JSON elegantly and safely can be hard, but Freddy is here to help. Freddy is a reusable framework for parsing JSON in Swift. It ha

[Deprecated] A shiny JSON parsing library in Swift :sparkles: Loved by many from 2015-2021
[Deprecated] A shiny JSON parsing library in Swift :sparkles: Loved by many from 2015-2021

🚨 Deprecation Notice 🚨 Gloss has been deprecated in favor of Swift's Codable framework. The existing Gloss source is not going away, however updates

HandyJSON is a framework written in Swift which to make converting model objects to and from JSON easy on iOS.

HandyJSON To deal with crash on iOS 14 beta4 please try version 5.0.3-beta HandyJSON is a framework written in Swift which to make converting model ob

Himotoki (紐解き) is a type-safe JSON decoding library written purely in Swift.

Himotoki Himotoki (紐解き) is a type-safe JSON decoding library written purely in Swift. This library is highly inspired by the popular Swift JSON parsin

JASON is a faster JSON deserializer written in Swift.
JASON is a faster JSON deserializer written in Swift.

JASON is a faster JSON deserializer written in Swift. JASON is the best framework we found to manage JSON at Swapcard. This is by far the fastest and

JSONHelper - ✌ Convert anything into anything in one operation; JSON data into class instances, hex strings into UIColor/NSColor, y/n strings to booleans, arrays and dictionaries of these; anything you can make sense of!

JSONHelper Convert anything into anything in one operation; hex strings into UIColor/NSColor, JSON strings into class instances, y/n strings to boolea

ObjectMapper is a framework written in Swift that makes it easy for you to convert your model objects to and from JSON.

ObjectMapper is a framework written in Swift that makes it easy for you to convert your model objects (classes and structs) to and from J

PMJSON provides a pure-Swift strongly-typed JSON encoder/decoder

Now Archived and Forked PMJSON will not be maintained in this repository going forward. Please use, create issues on, and make PRs to the fork of PMJS

JSONNeverDie - Auto reflection tool from JSON to Model, user friendly JSON encoder / decoder, aims to never die

JSONNeverDie is an auto reflection tool from JSON to Model, a user friendly JSON encoder / decoder, aims to never die. Also JSONNeverDie is a very important part of Pitaya.

John Lui 454 Oct 30, 2022
JSEN (JSON Swift Enum Notation) is a lightweight enum representation of a JSON, written in Swift.

JSEN /ˈdʒeɪsən/ JAY-sən JSEN (JSON Swift Enum Notation) is a lightweight enum representation of a JSON, written in Swift. A JSON, as defined in the EC

Roger Oba 8 Nov 22, 2022
JSON-Practice - JSON Practice With Swift

JSON Practice Vista creada con: Programmatic + AutoLayout Breve explicación de l

Vanesa Giselle Korbenfeld 0 Oct 29, 2021
Ss-json - High-performance json parsing in swift

json 0.1.1 swift-json is a pure-Swift JSON parsing library designed for high-per

kelvin 43 Dec 15, 2022
Swift-json - High-performance json parsing in swift

json 0.1.4 swift-json is a pure-Swift JSON parsing library designed for high-per

kelvin 43 Dec 15, 2022
Swift parser for JSON Feed — a new format similar to RSS and Atom but in JSON.

JSONFeed Swift parser for JSON Feed — a new format similar to RSS and Atom but in JSON. For more information about this new feed format visit: https:/

Toto Tvalavadze 31 Nov 22, 2021
AlamofireObjectMappe - An Alamofire extension which converts JSON response data into swift objects using ObjectMapper

AlamofireObjectMapper An extension to Alamofire which automatically converts JSON response data into swift objects using ObjectMapper. Usage Given a U

Tristan Himmelman 2.6k Dec 29, 2022
Functional JSON Parser - Linux Ready

Functional JSON Parser Feature Linux Ready Type-safe JSON parsing Functional value transformation Easy to parse nested value Dependency free No define

Ryo Aoyama 117 Sep 9, 2022
Argo is a library that lets you extract models from JSON or similar structures in a way that's concise, type-safe, and easy to extend

Argo is a library that lets you extract models from JSON or similar structures in a way that's concise, type-safe, and easy to extend. Using Argo

thoughtbot, inc. 3.5k Dec 20, 2022
Elevate is a JSON parsing framework that leverages Swift to make parsing simple, reliable and composable

Elevate is a JSON parsing framework that leverages Swift to make parsing simple, reliable and composable. Elevate should no longer be used for

Nike Inc. 611 Oct 23, 2022