[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"project-6667":3},{"id":4,"name":5,"fullName":6,"owner":5,"repo":5,"description":7,"homepage":8,"htmlUrl":9,"language":10,"languages":9,"totalLinesOfCode":9,"stars":11,"forks":12,"watchers":13,"openIssues":14,"contributorsCount":15,"subscribersCount":15,"size":15,"stars1d":15,"stars7d":16,"stars30d":17,"stars90d":15,"forks30d":15,"starsTrendScore":15,"compositeScore":18,"rankGlobal":9,"rankLanguage":9,"license":19,"archived":20,"fork":20,"defaultBranch":21,"hasWiki":20,"hasPages":20,"topics":22,"createdAt":9,"pushedAt":9,"updatedAt":33,"readmeContent":34,"aiSummary":35,"trendingCount":15,"starSnapshotCount":15,"syncStatus":16,"lastSyncTime":36,"discoverSource":37},6667,"SwiftyJSON","SwiftyJSON\u002FSwiftyJSON","The better way to deal with JSON data in Swift.","",null,"Swift",22955,3429,603,116,0,2,10,45,"MIT License",false,"master",[23,24,25,26,27,28,29,30,31,32],"carthage","cocoapods","json","json-parser","json-parsing-library","json-parsing-swift","request","response","swift","swiftyjson","2026-06-12 02:01:28","# SwiftyJSON\n\n[![CI](https:\u002F\u002Fgithub.com\u002FSwiftyJSON\u002FSwiftyJSON\u002Factions\u002Fworkflows\u002Fci.yml\u002Fbadge.svg)](https:\u002F\u002Fgithub.com\u002FSwiftyJSON\u002FSwiftyJSON\u002Factions\u002Fworkflows\u002Fci.yml)\n\n[![Carthage compatible](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FCarthage-compatible-4BC51D.svg?style=flat)](https:\u002F\u002Fgithub.com\u002FCarthage\u002FCarthage) ![CocoaPods](https:\u002F\u002Fimg.shields.io\u002Fcocoapods\u002Fv\u002FSwiftyJSON.svg) ![Platform](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002Fplatforms-iOS%208.0%20%7C%20macOS%2010.10%20%7C%20tvOS%209.0%20%7C%20watchOS%203.0-F28D00.svg) [![Reviewed by Hound](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FReviewed_by-Hound-8E64B0.svg)](https:\u002F\u002Fhoundci.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:\u002F\u002Fdeveloper.twitter.com\u002Fen\u002Fdocs\u002Ftweets\u002Ftimelines\u002Fapi-reference\u002Fget-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    \u002F\u002F 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        \u002F\u002F 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  \u002F\u002FNow 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    \u002F\u002FCalm down, take it easy, the \".string\" property still produces the correct Optional String type with safety\n} else {\n    \u002F\u002FPrint 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 16+\n- Swift 6.0+\n\n## Integration\n\n#### CocoaPods (iOS 8+, OS X 10.9+)\n\nYou can use [CocoaPods](http:\u002F\u002Fcocoapods.org\u002F) 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', '~> 4.0'\nend\n```\n\n#### Carthage (iOS 8+, OS X 10.9+)\n\nYou can use [Carthage](https:\u002F\u002Fgithub.com\u002FCarthage\u002FCarthage) to install `SwiftyJSON` by adding it to your `Cartfile`:\n\n```\ngithub \"SwiftyJSON\u002FSwiftyJSON\" ~> 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:\u002F\u002Fswift.org\u002Fpackage-manager) to install `SwiftyJSON` by adding the proper description to your `Package.swift` file:\n\n```swift\n\u002F\u002F swift-tools-version:4.0\nimport PackageDescription\n\nlet package = Package(\n    name: \"YOUR_PROJECT_NAME\",\n    dependencies: [\n        .package(url: \"https:\u002F\u002Fgithub.com\u002FSwiftyJSON\u002FSwiftyJSON.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\u002F\u002F Getting a double from a JSON Array\nlet name = json[0].double\n```\n\n```swift\n\u002F\u002F Getting an array of string from a JSON Array\nlet arrayNames =  json[\"users\"].arrayValue.map {$0[\"name\"].stringValue}\n```\n\n```swift\n\u002F\u002F Getting a string from a JSON Dictionary\nlet name = json[\"name\"].stringValue\n```\n\n```swift\n\u002F\u002F Getting a string using a path to the element\nlet path: [JSONSubscriptType] = [1,\"list\",2,\"name\"]\nlet name = json[path].string\n\u002F\u002F Just the same\nlet name = json[1][\"list\"][2][\"name\"].string\n\u002F\u002F Alternatively\nlet name = json[1,\"list\",2,\"name\"].string\n```\n\n```swift\n\u002F\u002F With a hard way\nlet name = json[].string\n```\n\n```swift\n\u002F\u002F With a custom way\nlet keys:[JSONSubscriptType] = [1,\"list\",2,\"name\"]\nlet name = json[keys].string\n```\n\n#### Loop\n\n```swift\n\u002F\u002F If json is .Dictionary\nfor (key,subJson):(String, JSON) in json {\n   \u002F\u002F 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\u002F\u002F If json is .Array\n\u002F\u002F The `index` is 0..\u003Cjson.count's string value\nfor (index,subJson):(String, JSON) in json {\n    \u002F\u002F 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\u002Fset 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    \u002F\u002F Do something you want\n} else {\n    print(json[999].error!) \u002F\u002F \"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    \u002F\u002F Do something you want\n} else {\n    print(json[\"address\"].error!) \u002F\u002F \"Dictionary[\"address\"] does not exist\"\n}\n```\n\n```swift\nlet json = JSON(12345)\nif let age = json[0].string {\n    \u002F\u002F Do something you want\n} else {\n    print(json[0])       \u002F\u002F \"Array[0] failure, It is not an array\"\n    print(json[0].error!) \u002F\u002F \"Array[0] failure, It is not an array\"\n}\n\nif let name = json[\"name\"].string {\n    \u002F\u002F Do something you want\n} else {\n    print(json[\"name\"])       \u002F\u002F \"Dictionary[\\\"name\"] failure, It is not an dictionary\"\n    print(json[\"name\"].error!) \u002F\u002F \"Dictionary[\\\"name\"] failure, It is not an dictionary\"\n}\n```\n\n#### Optional getter\n\n```swift\n\u002F\u002F NSNumber\nif let id = json[\"user\"][\"favourites_count\"].number {\n   \u002F\u002F Do something you want\n} else {\n   \u002F\u002F Print the error\n   print(json[\"user\"][\"favourites_count\"].error!)\n}\n```\n\n```swift\n\u002F\u002F String\nif let id = json[\"user\"][\"name\"].string {\n   \u002F\u002F Do something you want\n} else {\n   \u002F\u002F Print the error\n   print(json[\"user\"][\"name\"].error!)\n}\n```\n\n```swift\n\u002F\u002F Bool\nif let id = json[\"user\"][\"is_translator\"].bool {\n   \u002F\u002F Do something you want\n} else {\n   \u002F\u002F Print the error\n   print(json[\"user\"][\"is_translator\"].error!)\n}\n```\n\n```swift\n\u002F\u002F Int\nif let id = json[\"user\"][\"id\"].int {\n   \u002F\u002F Do something you want\n} else {\n   \u002F\u002F 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\u002F\u002F If not a Number or nil, return 0\nlet id: Int = json[\"id\"].intValue\n```\n\n```swift\n\u002F\u002F If not a String or nil, return \"\"\nlet name: String = json[\"name\"].stringValue\n```\n\n```swift\n\u002F\u002F If not an Array or nil, return []\nlet list: Array\u003CJSON> = json[\"list\"].arrayValue\n```\n\n```swift\n\u002F\u002F If not a Dictionary or nil, return [:]\nlet user: Dictionary\u003CString, JSON> = 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\u002F\u002Fconvert the JSON to raw NSData\ndo {\n\tlet rawData = try json.rawData()\n  \u002F\u002FDo something you want\n} catch {\n\tprint(\"Error \\(error)\")\n}\n```\n\n```swift\n\u002F\u002Fconvert the JSON to a raw String\nif let rawString = json.rawString() {\n  \u002F\u002FDo something you want\n} else {\n\tprint(\"json.rawString is nil\")\n}\n```\n\n#### Existence\n\n```swift\n\u002F\u002F 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:\u002F\u002Fnshipster.com\u002Fswift-literal-convertible\u002F)\n\n```swift\n\u002F\u002F StringLiteralConvertible\nlet json: JSON = \"I'm a json\"\n```\n\n```swift\n\u002F\u002F IntegerLiteralConvertible\nlet json: JSON =  12345\n```\n\n```swift\n\u002F\u002F BooleanLiteralConvertible\nlet json: JSON =  true\n```\n\n```swift\n\u002F\u002F FloatLiteralConvertible\nlet json: JSON =  2.8765\n```\n\n```swift\n\u002F\u002F DictionaryLiteralConvertible\nlet json: JSON =  [\"I\":\"am\", \"a\":\"json\"]\n```\n\n```swift\n\u002F\u002F ArrayLiteralConvertible\nlet json: JSON =  [\"I\", \"am\", \"a\", \"json\"]\n```\n\n```swift\n\u002F\u002F With subscript in array\nvar json: JSON =  [1,2,3]\njson[0] = 100\njson[1] = 200\njson[2] = 300\njson[999] = 300 \u002F\u002F Don't worry, nothing will happen\n```\n\n```swift\n\u002F\u002F With subscript in dictionary\nvar json: JSON =  [\"name\": \"Jack\", \"age\": 25]\njson[\"name\"] = \"Mike\"\njson[\"age\"] = \"25\" \u002F\u002F It's OK to set String\njson[\"address\"] = \"L.A.\" \u002F\u002F Add the \"address\": \"L.A.\" in json\n```\n\n```swift\n\u002F\u002F Array & 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\u002F\u002F With other JSON objects\nlet user: JSON = [\"username\" : \"Steve\", \"password\": \"supersecurepassword\"]\nlet auth: JSON = [\n  \"user\": user.object, \u002F\u002F 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\u002F\u002F [\n\u002F\u002F     \"first_name\": \"John\",\n\u002F\u002F     \"last_name\": \"Doe\",\n\u002F\u002F     \"age\": 21,\n\u002F\u002F     \"skills\": [\"Coding\", \"Reading\", \"Writing\"],\n\u002F\u002F     \"address\": [\n\u002F\u002F         \"street\": \"Front St\",\n\u002F\u002F         \"zip\": \"12342\",\n\u002F\u002F         \"city\": \"New York City\"\n\u002F\u002F     ]\n\u002F\u002F ]\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\u002F\u002F representation is \"{\\\"1\\\":2,\\\"2\\\":\\\"two\\\",\\\"3\\\":null}\", which represents {\"1\":2,\"2\":\"two\",\"3\":null}\n```\n\n## Work with [Alamofire](https:\u002F\u002Fgithub.com\u002FAlamofire\u002FAlamofire)\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:\u002F\u002Fgithub.com\u002FSwiftyJSON\u002FAlamofire-SwiftyJSON)\n\n\n## Work with [Moya](https:\u002F\u002Fgithub.com\u002FMoya\u002FMoya)\n\nSwiftyJSON parse data to JSON:\n\n```swift\nlet provider = MoyaProvider\u003CBackend>()\nprovider.request(.showProducts) { result in\n    switch result {\n    case let .success(moyaResponse):\n        let data = moyaResponse.data\n        let json = JSON(data: data) \u002F\u002F 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:\u002F\u002Fgithub.com\u002FAhmed-Ali\u002FJSONExport)\n","SwiftyJSON 是一个用于简化 Swift 中 JSON 数据处理的库。它通过提供简洁易用的 API 来解析和操作 JSON 数据，使得开发者可以轻松访问 JSON 对象中的值而无需处理繁琐的类型转换和可选链。该库支持多种集成方式，包括 Carthage 和 CocoaPods，并且适用于 iOS 8.0、macOS 10.10、tvOS 9.0 及 watchOS 3.0 以上平台。SwiftyJSON 特别适合需要频繁与 JSON 格式数据交互的应用场景，如网络请求响应解析、配置文件读取等，能够显著提高开发效率并减少代码复杂度。","2026-06-11 03:08:10","top_language"]