{"id":1711,"url":"https://github.com/SwiftyJSON/SwiftyJSON","last_synced_at":"2025-08-06T13:32:10.491Z","repository":{"id":40652025,"uuid":"20965586","full_name":"SwiftyJSON/SwiftyJSON","owner":"SwiftyJSON","description":"The better way to deal with JSON data in Swift.","archived":false,"fork":false,"pushed_at":"2025-05-27T07:57:34.000Z","size":1164,"stargazers_count":22895,"open_issues_count":134,"forks_count":3448,"subscribers_count":610,"default_branch":"master","last_synced_at":"2025-08-01T01:07:56.798Z","etag":null,"topics":["carthage","cocoapods","json","json-parser","json-parsing-library","json-parsing-swift","request","response","swift","swiftyjson"],"latest_commit_sha":null,"homepage":"","language":"Swift","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/SwiftyJSON.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2014-06-18T14:41:15.000Z","updated_at":"2025-07-31T23:02:35.000Z","dependencies_parsed_at":"2022-08-10T00:00:49.667Z","dependency_job_id":"a8562980-9278-4606-8226-9ba078496fb3","html_url":"https://github.com/SwiftyJSON/SwiftyJSON","commit_stats":{"total_commits":521,"total_committers":162,"mean_commits":"3.2160493827160495","dds":0.8023032629558542,"last_synced_commit":"c761b43aa03f15f00df64744e70399d78c3bee96"},"previous_names":[],"tags_count":29,"template":false,"template_full_name":null,"purl":"pkg:github/SwiftyJSON/SwiftyJSON","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/SwiftyJSON%2FSwiftyJSON","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/SwiftyJSON%2FSwiftyJSON/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/SwiftyJSON%2FSwiftyJSON/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/SwiftyJSON%2FSwiftyJSON/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/SwiftyJSON","download_url":"https://codeload.github.com/SwiftyJSON/SwiftyJSON/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/SwiftyJSON%2FSwiftyJSON/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":268317749,"owners_count":24231417,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-08-01T02:00:08.611Z","response_time":67,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["carthage","cocoapods","json","json-parser","json-parsing-library","json-parsing-swift","request","response","swift","swiftyjson"],"created_at":"2024-01-05T20:15:53.994Z","updated_at":"2025-08-06T13:32:10.480Z","avatar_url":"https://github.com/SwiftyJSON.png","language":"Swift","funding_links":[],"categories":["Parsing","Libs","Libraries","Utilities","Swift","IOS 或 OSX","Swift 库","JSON/XML Manipulation","Libraries by Language","\u003ca name=\"for-projects\"\u003e\u003c/a\u003e For Projects","JSON Parse","Data Management [🔝](#readme)","9. 其他与展望","Frameworks","JSON","Major","JSONSerialization"],"sub_categories":["JSON","Data Management","Other free courses","Swift","\u003ca name=\"for-projects-example-projects\"\u003e\u003c/a\u003e Example Projects","5. 参考材料","Network","JSON Parser Library"],"readme":"# SwiftyJSON\n\n[![CI](https://github.com/SwiftyJSON/SwiftyJSON/actions/workflows/ci.yml/badge.svg)](https://github.com/SwiftyJSON/SwiftyJSON/actions/workflows/ci.yml)\n\n[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) ![CocoaPods](https://img.shields.io/cocoapods/v/SwiftyJSON.svg) ![Platform](https://img.shields.io/badge/platforms-iOS%208.0%20%7C%20macOS%2010.10%20%7C%20tvOS%209.0%20%7C%20watchOS%203.0-F28D00.svg) [![Reviewed by Hound](https://img.shields.io/badge/Reviewed_by-Hound-8E64B0.svg)](https://houndci.com)\n\nSwiftyJSON makes it easy to deal with JSON data in Swift.\n\n1. [Why is the typical JSON handling in Swift NOT good](#why-is-the-typical-json-handling-in-swift-not-good)\n2. [Requirements](#requirements)\n3. [Integration](#integration)\n4. [Usage](#usage)\n   - [Initialization](#initialization)\n   - [Subscript](#subscript)\n   - [Loop](#loop)\n   - [Error](#error)\n   - [Optional getter](#optional-getter)\n   - [Non-optional getter](#non-optional-getter)\n   - [Setter](#setter)\n   - [Raw object](#raw-object)\n   - [Literal convertibles](#literal-convertibles)\n   - [Merging](#merging)\n   - [Removing elements](#removing-elements)\n5. [Work with Alamofire](#work-with-alamofire)\n6. [Work with Moya](#work-with-moya)\n7. [SwiftyJSON Model Generator](#swiftyjson-model-generator)\n\n\n## Why is the typical JSON handling in Swift NOT good?\n\nSwift is very strict about types. But although explicit typing is good for saving us from mistakes, it becomes painful when dealing with JSON and other areas that are, by nature, implicit about types.\n\nTake the Twitter API for example. Say we want to retrieve a user's \"name\" value of some tweet in Swift (according to [Twitter's API](https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline)).\n\nThe code would look like this:\n\n```swift\nif let statusesArray = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [[String: Any]],\n    let user = statusesArray[0][\"user\"] as? [String: Any],\n    let username = user[\"name\"] as? String {\n    // Finally we got the username\n}\n```\n\nIt's not good.\n\nEven if we use optional chaining, it would be messy:\n\n```swift\nif let JSONObject = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [[String: Any]],\n    let username = (JSONObject[0][\"user\"] as? [String: Any])?[\"name\"] as? String {\n        // There's our username\n}\n```\n\nAn unreadable mess--for something that should really be simple!\n\nWith SwiftyJSON all you have to do is:\n\n```swift\nlet json = try? JSON(data: dataFromNetworking)\nif let userName = json[0][\"user\"][\"name\"].string {\n  //Now you got your value\n}\n```\n\nAnd don't worry about the Optional Wrapping thing. It's done for you automatically.\n\n```swift\nlet json = try? JSON(data: dataFromNetworking)\nlet result = json[999999][\"wrong_key\"][\"wrong_name\"]\nif let userName = result.string {\n    //Calm down, take it easy, the \".string\" property still produces the correct Optional String type with safety\n} else {\n    //Print the error\n    print(result.error)\n}\n```\n\n## Requirements\n\n- iOS 8.0+ | macOS 10.10+ | tvOS 9.0+ | watchOS 2.0+\n- Xcode 8\n\n## Integration\n\n#### CocoaPods (iOS 8+, OS X 10.9+)\n\nYou can use [CocoaPods](http://cocoapods.org/) to install `SwiftyJSON` by adding it to your `Podfile`:\n\n```ruby\nplatform :ios, '8.0'\nuse_frameworks!\n\ntarget 'MyApp' do\n    pod 'SwiftyJSON', '~\u003e 4.0'\nend\n```\n\n#### Carthage (iOS 8+, OS X 10.9+)\n\nYou can use [Carthage](https://github.com/Carthage/Carthage) to install `SwiftyJSON` by adding it to your `Cartfile`:\n\n```\ngithub \"SwiftyJSON/SwiftyJSON\" ~\u003e 4.0\n```\n\nIf you use Carthage to build your dependencies, make sure you have added `SwiftyJSON.framework` to the \"Linked Frameworks and Libraries\" section of your target, and have included them in your Carthage framework copying build phase.\n\n#### Swift Package Manager\n\nYou can use [The Swift Package Manager](https://swift.org/package-manager) to install `SwiftyJSON` by adding the proper description to your `Package.swift` file:\n\n```swift\n// swift-tools-version:4.0\nimport PackageDescription\n\nlet package = Package(\n    name: \"YOUR_PROJECT_NAME\",\n    dependencies: [\n        .package(url: \"https://github.com/SwiftyJSON/SwiftyJSON.git\", from: \"4.0.0\"),\n    ]\n)\n```\nThen run `swift build` whenever you get prepared.\n\n#### Manually (iOS 7+, OS X 10.9+)\n\nTo use this library in your project manually you may:  \n\n1. for Projects, just drag SwiftyJSON.swift to the project tree\n2. for Workspaces, include the whole SwiftyJSON.xcodeproj\n\n## Usage\n\n#### Initialization\n\n```swift\nimport SwiftyJSON\n```\n\n```swift\nlet json = try? JSON(data: dataFromNetworking)\n```\nOr\n\n```swift\nlet json = JSON(jsonObject)\n```\nOr\n\n```swift\nif let dataFromString = jsonString.data(using: .utf8, allowLossyConversion: false) {\n    let json = JSON(data: dataFromString)\n}\n```\n\n#### Subscript\n\n```swift\n// Getting a double from a JSON Array\nlet name = json[0].double\n```\n\n```swift\n// Getting an array of string from a JSON Array\nlet arrayNames =  json[\"users\"].arrayValue.map {$0[\"name\"].stringValue}\n```\n\n```swift\n// Getting a string from a JSON Dictionary\nlet name = json[\"name\"].stringValue\n```\n\n```swift\n// Getting a string using a path to the element\nlet path: [JSONSubscriptType] = [1,\"list\",2,\"name\"]\nlet name = json[path].string\n// Just the same\nlet name = json[1][\"list\"][2][\"name\"].string\n// Alternatively\nlet name = json[1,\"list\",2,\"name\"].string\n```\n\n```swift\n// With a hard way\nlet name = json[].string\n```\n\n```swift\n// With a custom way\nlet keys:[JSONSubscriptType] = [1,\"list\",2,\"name\"]\nlet name = json[keys].string\n```\n\n#### Loop\n\n```swift\n// If json is .Dictionary\nfor (key,subJson):(String, JSON) in json {\n   // Do something you want\n}\n```\n\n*The first element is always a String, even if the JSON is an Array*\n\n```swift\n// If json is .Array\n// The `index` is 0..\u003cjson.count's string value\nfor (index,subJson):(String, JSON) in json {\n    // Do something you want\n}\n```\n\n#### Error\n\n##### SwiftyJSON 4.x\n\nSwiftyJSON 4.x introduces an enum type called `SwiftyJSONError`, which includes `unsupportedType`, `indexOutOfBounds`, `elementTooDeep`, `wrongType`, `notExist` and `invalidJSON`, at the same time, `ErrorDomain` are being replaced by `SwiftyJSONError.errorDomain`.\nNote: Those old error types are deprecated in SwiftyJSON 4.x and will be removed in the future release.\n\n##### SwiftyJSON 3.x\n\nUse a subscript to get/set a value in an Array or Dictionary\n\nIf the JSON is:\n*  an array, the app may crash with \"index out-of-bounds.\"\n*  a dictionary, it will be assigned to `nil` without a reason.\n*  not an array or a dictionary, the app may crash with an \"unrecognised selector\" exception.\n\nThis will never happen in SwiftyJSON.\n\n```swift\nlet json = JSON([\"name\", \"age\"])\nif let name = json[999].string {\n    // Do something you want\n} else {\n    print(json[999].error!) // \"Array[999] is out of bounds\"\n}\n```\n\n```swift\nlet json = JSON([\"name\":\"Jack\", \"age\": 25])\nif let name = json[\"address\"].string {\n    // Do something you want\n} else {\n    print(json[\"address\"].error!) // \"Dictionary[\"address\"] does not exist\"\n}\n```\n\n```swift\nlet json = JSON(12345)\nif let age = json[0].string {\n    // Do something you want\n} else {\n    print(json[0])       // \"Array[0] failure, It is not an array\"\n    print(json[0].error!) // \"Array[0] failure, It is not an array\"\n}\n\nif let name = json[\"name\"].string {\n    // Do something you want\n} else {\n    print(json[\"name\"])       // \"Dictionary[\\\"name\"] failure, It is not an dictionary\"\n    print(json[\"name\"].error!) // \"Dictionary[\\\"name\"] failure, It is not an dictionary\"\n}\n```\n\n#### Optional getter\n\n```swift\n// NSNumber\nif let id = json[\"user\"][\"favourites_count\"].number {\n   // Do something you want\n} else {\n   // Print the error\n   print(json[\"user\"][\"favourites_count\"].error!)\n}\n```\n\n```swift\n// String\nif let id = json[\"user\"][\"name\"].string {\n   // Do something you want\n} else {\n   // Print the error\n   print(json[\"user\"][\"name\"].error!)\n}\n```\n\n```swift\n// Bool\nif let id = json[\"user\"][\"is_translator\"].bool {\n   // Do something you want\n} else {\n   // Print the error\n   print(json[\"user\"][\"is_translator\"].error!)\n}\n```\n\n```swift\n// Int\nif let id = json[\"user\"][\"id\"].int {\n   // Do something you want\n} else {\n   // Print the error\n   print(json[\"user\"][\"id\"].error!)\n}\n...\n```\n\n#### Non-optional getter\n\nNon-optional getter is named `xxxValue`\n\n```swift\n// If not a Number or nil, return 0\nlet id: Int = json[\"id\"].intValue\n```\n\n```swift\n// If not a String or nil, return \"\"\nlet name: String = json[\"name\"].stringValue\n```\n\n```swift\n// If not an Array or nil, return []\nlet list: Array\u003cJSON\u003e = json[\"list\"].arrayValue\n```\n\n```swift\n// If not a Dictionary or nil, return [:]\nlet user: Dictionary\u003cString, JSON\u003e = json[\"user\"].dictionaryValue\n```\n\n#### Setter\n\n```swift\njson[\"name\"] = JSON(\"new-name\")\njson[0] = JSON(1)\n```\n\n```swift\njson[\"id\"].int =  1234567890\njson[\"coordinate\"].double =  8766.766\njson[\"name\"].string =  \"Jack\"\njson.arrayObject = [1,2,3,4]\njson.dictionaryObject = [\"name\":\"Jack\", \"age\":25]\n```\n\n#### Raw object\n\n```swift\nlet rawObject: Any = json.object\n```\n\n```swift\nlet rawValue: Any = json.rawValue\n```\n\n```swift\n//convert the JSON to raw NSData\ndo {\n\tlet rawData = try json.rawData()\n  //Do something you want\n} catch {\n\tprint(\"Error \\(error)\")\n}\n```\n\n```swift\n//convert the JSON to a raw String\nif let rawString = json.rawString() {\n  //Do something you want\n} else {\n\tprint(\"json.rawString is nil\")\n}\n```\n\n#### Existence\n\n```swift\n// shows you whether value specified in JSON or not\nif json[\"name\"].exists()\n```\n\n#### Literal convertibles\n\nFor more info about literal convertibles: [Swift Literal Convertibles](http://nshipster.com/swift-literal-convertible/)\n\n```swift\n// StringLiteralConvertible\nlet json: JSON = \"I'm a json\"\n```\n\n```swift\n// IntegerLiteralConvertible\nlet json: JSON =  12345\n```\n\n```swift\n// BooleanLiteralConvertible\nlet json: JSON =  true\n```\n\n```swift\n// FloatLiteralConvertible\nlet json: JSON =  2.8765\n```\n\n```swift\n// DictionaryLiteralConvertible\nlet json: JSON =  [\"I\":\"am\", \"a\":\"json\"]\n```\n\n```swift\n// ArrayLiteralConvertible\nlet json: JSON =  [\"I\", \"am\", \"a\", \"json\"]\n```\n\n```swift\n// With subscript in array\nvar json: JSON =  [1,2,3]\njson[0] = 100\njson[1] = 200\njson[2] = 300\njson[999] = 300 // Don't worry, nothing will happen\n```\n\n```swift\n// With subscript in dictionary\nvar json: JSON =  [\"name\": \"Jack\", \"age\": 25]\njson[\"name\"] = \"Mike\"\njson[\"age\"] = \"25\" // It's OK to set String\njson[\"address\"] = \"L.A.\" // Add the \"address\": \"L.A.\" in json\n```\n\n```swift\n// Array \u0026 Dictionary\nvar json: JSON =  [\"name\": \"Jack\", \"age\": 25, \"list\": [\"a\", \"b\", \"c\", [\"what\": \"this\"]]]\njson[\"list\"][3][\"what\"] = \"that\"\njson[\"list\",3,\"what\"] = \"that\"\nlet path: [JSONSubscriptType] = [\"list\",3,\"what\"]\njson[path] = \"that\"\n```\n\n```swift\n// With other JSON objects\nlet user: JSON = [\"username\" : \"Steve\", \"password\": \"supersecurepassword\"]\nlet auth: JSON = [\n  \"user\": user.object, // use user.object instead of just user\n  \"apikey\": \"supersecretapitoken\"\n]\n```\n\n#### Merging\n\nIt is possible to merge one JSON into another JSON. Merging a JSON into another JSON adds all non existing values to the original JSON which are only present in the `other` JSON.\n\nIf both JSONs contain a value for the same key, _mostly_ this value gets overwritten in the original JSON, but there are two cases where it provides some special treatment:\n\n- In case of both values being a `JSON.Type.array` the values form the array found in the `other` JSON getting appended to the original JSON's array value.\n- In case of both values being a `JSON.Type.dictionary` both JSON-values are getting merged the same way the encapsulating JSON is merged.\n\nIn a case where two fields in a JSON have different types, the value will get always overwritten.\n\nThere are two different fashions for merging: `merge` modifies the original JSON, whereas `merged` works non-destructively on a copy.\n\n```swift\nlet original: JSON = [\n    \"first_name\": \"John\",\n    \"age\": 20,\n    \"skills\": [\"Coding\", \"Reading\"],\n    \"address\": [\n        \"street\": \"Front St\",\n        \"zip\": \"12345\",\n    ]\n]\n\nlet update: JSON = [\n    \"last_name\": \"Doe\",\n    \"age\": 21,\n    \"skills\": [\"Writing\"],\n    \"address\": [\n        \"zip\": \"12342\",\n        \"city\": \"New York City\"\n    ]\n]\n\nlet updated = original.merge(with: update)\n// [\n//     \"first_name\": \"John\",\n//     \"last_name\": \"Doe\",\n//     \"age\": 21,\n//     \"skills\": [\"Coding\", \"Reading\", \"Writing\"],\n//     \"address\": [\n//         \"street\": \"Front St\",\n//         \"zip\": \"12342\",\n//         \"city\": \"New York City\"\n//     ]\n// ]\n```\n\n\n#### Removing elements\n\nIf you are storing dictionaries, you can remove elements using `dictionaryObject.removeValue(forKey:)`. This mutates the JSON object in place.\n\nFor example:\n\n```swift\nvar object = JSON([\n    \"one\": [\"color\": \"blue\"],\n    \"two\": [\"city\": \"tokyo\",\n            \"country\": \"japan\",\n            \"foods\": [\n                \"breakfast\": \"tea\",\n                \"lunch\": \"sushi\"\n                ]\n            ]\n])\n```\n\nLets remove the `country` key:\n\n```swift\nobject[\"two\"].dictionaryObject?.removeValue(forKey: \"country\")\n```\n\nIf you `print(object)`, you'll see that the `country` key no longer exists.\n\n```json\n{\n  \"one\" : {\n    \"color\" : \"blue\"\n  },\n  \"two\" : {\n    \"city\" : \"tokyo\",\n    \"foods\" : {\n      \"breakfast\" : \"tea\",\n      \"lunch\" : \"sushi\"\n    }\n  }\n}\n```\n\nThis also works for nested dictionaries:\n\n```swift\nobject[\"two\"][\"foods\"].dictionaryObject?.removeValue(forKey: \"breakfast\")\n```\n\n```json\n{\n  \"one\" : {\n    \"color\" : \"blue\"\n  },\n  \"two\" : {\n    \"city\" : \"tokyo\",\n    \"foods\" : {\n      \"lunch\" : \"sushi\"\n    }\n  }\n}\n```\n\n## String representation\nThere are two options available:\n- use the default Swift one\n- use a custom one that will handle optionals well and represent `nil` as `\"null\"`:\n```swift\nlet dict = [\"1\":2, \"2\":\"two\", \"3\": nil] as [String: Any?]\nlet json = JSON(dict)\nlet representation = json.rawString(options: [.castNilToNSNull: true])\n// representation is \"{\\\"1\\\":2,\\\"2\\\":\\\"two\\\",\\\"3\\\":null}\", which represents {\"1\":2,\"2\":\"two\",\"3\":null}\n```\n\n## Work with [Alamofire](https://github.com/Alamofire/Alamofire)\n\nSwiftyJSON nicely wraps the result of the Alamofire JSON response handler:\n\n```swift\nAlamofire.request(url, method: .get).validate().responseJSON { response in\n    switch response.result {\n    case .success(let value):\n        let json = JSON(value)\n        print(\"JSON: \\(json)\")\n    case .failure(let error):\n        print(error)\n    }\n}\n```\n\nWe also provide an extension of Alamofire for serializing NSData to SwiftyJSON's JSON.\n\nSee: [Alamofire-SwiftyJSON](https://github.com/SwiftyJSON/Alamofire-SwiftyJSON)\n\n\n## Work with [Moya](https://github.com/Moya/Moya)\n\nSwiftyJSON parse data to JSON:\n\n```swift\nlet provider = MoyaProvider\u003cBackend\u003e()\nprovider.request(.showProducts) { result in\n    switch result {\n    case let .success(moyaResponse):\n        let data = moyaResponse.data\n        let json = JSON(data: data) // convert network data to json\n        print(json)\n    case let .failure(error):\n        print(\"error: \\(error)\")\n    }\n}\n\n```\n\n## SwiftyJSON Model Generator\nTools to generate SwiftyJSON Models\n* [JSON Export](https://github.com/Ahmed-Ali/JSONExport)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FSwiftyJSON%2FSwiftyJSON","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FSwiftyJSON%2FSwiftyJSON","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FSwiftyJSON%2FSwiftyJSON/lists"}