# Swift Language Reading & Writing JSON SwiftyJSON

## Example

SwiftyJSON is a Swift framework built to remove the need for optional chaining in normal JSON serialization.

Without SwiftyJSON, your code would look like this to find the name of the first book in a JSON object:

``````if let jsonObject = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) as? [[String: AnyObject]],
let bookName = (jsonObject["book"] as? [String: AnyObject])?["name"] as? String {
//We can now use the book name
}
``````

In SwiftyJSON, this is hugely simplified:

``````let json = JSON(data: data)
if let bookName = json["book"]["name"].string {
//We can now use the book name
}
``````

It removes the need to check every field, as it will return nil if any of them are invalid.

To use SwiftyJSON, download the correct version from the Git repository - there is a branch for Swift 3. Simply drag the "SwiftyJSON.swift" into your project and import into your class:

``````import SwiftyJSON
``````

You can create your JSON object using the following two initializers:

``````let jsonObject = JSON(data: dataObject)
``````

or

``````let jsonObject = JSON(jsonObject) //This could be a string in a JSON format for example
``````

To access your data, use subscripts:

``````let firstObjectInAnArray = jsonObject
let nameOfFirstObject = jsonObject["name"]
``````

You can then parse your value to a certain data type, which will return an optional value:

``````let nameOfFirstObject = jsonObject["name"].string //This will return the name as a string

let nameOfFirstObject = jsonObject["name"].double //This will return null
``````

You can also compile your paths into a swift Array:

``````let convolutedPath = jsonObject["name"]["lastName"]["firstLetter"].string
``````

Is the same as:

``````let convolutedPath = jsonObject[0, "name", 2, "lastName", "firstLetter"].string
``````

SwiftyJSON also has functionality to print its own errors:

``````if let name = json.string {
//You can use the value - it is valid
} else {
print(json.error) // "Array is out of bounds" - You cant use the value
}
``````

If you need to write to your JSON object, you can use subscripts again:

``````var originalJSON:JSON = ["name": "Jack", "age": 18]
originalJSON["age"] = 25 //This changes the age to 25
originalJSON["surname"] = "Smith" //This creates a new field called "surname" and adds the value to it
``````

Should you need the original String for the JSON, for example if you need to write it to a file, you can get the raw value out:

``````if let string = json.rawString() { //This is a String object
//Write the string to a file if you like
}

if let data = json.rawData() { //This is an NSData object
//Send the data to your server if you like
}
``````
{"ft_lang_label":"__label__en","ft_lang_prob":0.63346136,"math_prob":0.5143473,"size":2624,"snap":"2022-40-2023-06","text_gpt3_token_len":664,"char_repetition_ratio":0.15229008,"word_repetition_ratio":0.024390243,"special_character_ratio":0.25838414,"punctuation_ratio":0.11825726,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9665893,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2022-10-03T17:16:35Z\",\"WARC-Record-ID\":\"<urn:uuid:295e84d8-ba27-4dcd-b115-d707047fe3a3>\",\"Content-Length\":\"44785\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:55a5471b-7b97-4b2e-a893-814ad1f2be54>\",\"WARC-Concurrent-To\":\"<urn:uuid:f32fc2ce-7180-4804-9ba1-41e3fd3470fa>\",\"WARC-IP-Address\":\"40.83.160.29\",\"WARC-Target-URI\":\"https://riptutorial.com/swift/example/3882/swiftyjson\",\"WARC-Payload-Digest\":\"sha1:F64NLBBTUGVBKY6VHRPTHM2JNH3PA4IK\",\"WARC-Block-Digest\":\"sha1:RHBUDSREWHQRNKZFJQOQMBK4ECE7TZEF\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2022/CC-MAIN-2022-40/CC-MAIN-2022-40_segments_1664030337428.0_warc_CC-MAIN-20221003164901-20221003194901-00680.warc.gz\"}"}