How to parse a JSON file in swift?

swift read json file from documents directory
create json file in xcode
swift json parsing example
create json file in swift
swift parse json
swift data from file
swift 5 get json from url
update json file swift

I have a JSON file, want to parse and use list of objects in table view. Can any one share the code to parse JSON file in swift.

Couldn't be more simple:

import Foundation

let jsonData: Data = /* get your json data */
let jsonDict = try JSONSerialization.jsonObject(with: jsonData) as? NSDictionary

That being said, I strongly recommend using Codable APIs introduced in Swift 4.

How to Parse JSON from File & URL (in swift 4.2), JSON stands for JavaScript Object Notation and is a minimal, readable format for structuring data. It is used to transmit data between a server  Parse JSON from file and URL with Swift Step 1: Create the local JSON file The first thing that we need to do is create our local JSON file. To add a blank file Step 2: Create the Codeable Struct Now that we have our data.json file we need to create our codeable Struct that will Step 3: Read

Making the API Request

var request: NSURLRequest = NSURLRequest(URL: url)
var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: false)

Preparing for the response

Declare an array as below

var data: NSMutableData = NSMutableData()

Receiving the response


func connection(didReceiveResponse: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {
   // Received a new request, clear out the data object = NSMutableData()


func connection(connection: NSURLConnection!, didReceiveData data: NSData!) {
   // Append the received chunk of data to our data object


func connectionDidFinishLoading(connection: NSURLConnection!) {
   // Request complete, should now hold the resulting info
   // Convert the retrieved data in to an object through JSON deserialization
   var err: NSError
   var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary

   if jsonResult.count>0 && jsonResult["results"].count>0 {
      var results: NSArray = jsonResult["results"] as NSArray
      self.tableData = results


When NSURLConnection receives a response, we can expect the didReceiveResponse method to be called on our behalf. At this point we simply reset our data by saying = NSMutableData(), creating a new empty data object.

After a connection is made, we will start receiving data in the method didReceiveData. The data argument being passed in here is where all our juicy information comes from. We need to hold on to each chunk that comes in, so we append it to the object we cleared out earlier.

Finally, when the connection is done and all data has been received, connectionDidFinishLoading is called and we’re ready to use the data in our app. Hooray!

The connectionDidFinishLoading method here uses the NSJSONSerialization class to convert our raw data in to useful Dictionary objects by deserializing the results from your Url.

Parse JSON from file and URL with Swift, Parse JSON from file and URL with Swift. Parse JSON from file and URL with Swift. In todays tutorial we are going to learn how to read a JSON  Open the podfile and add the SwiftyJSON pod Open the Podfile in Textedit and add the line pod “SwiftyJSON”, “ [version number]” or just simply pod “SwiftyJSON” Save the file and in your terminal do a pod install, once it has finished installation it should have created a Pods folder, [projectname].xcworkspace, and a Podfile.lock.

How to Read data from local JSON file in Swift?, We will assume that we want to have a JSON file added inside our project and want to access its data in swift language. Code. You can create a  I have a JSON file, want to parse and use list of objects in table view. Can any one share the code to parse JSON file in swift.

Here is a code to make the conversions between JSON and NSData in Swift 2.0

// Convert from NSData to json object
func nsdataToJSON(data: NSData) -> AnyObject? {
    do {
        return try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers)
    } catch let myJSONError {
    return nil

// Convert from JSON to nsdata
func jsonToNSData(json: AnyObject) -> NSData?{
    do {
        return try NSJSONSerialization.dataWithJSONObject(json, options: NSJSONWritingOptions.PrettyPrinted)
    } catch let myJSONError {
    return nil;

How to Parse Local Json Files using Swift (Xcode/2020), Swift JSON Parsing Tutorial, iOS JSON Parse example, Parse JSON file in iOS app using Swift, Swift JSON Tutorial, Swift JSONSerialization example code. Open and Run Xcode and create a new project with File » New » Project ⌘⇧N. Select iOS » Application » Single View Application: Here, there will be two methods to load JSON Data one way will be through the .json file which will be stored in out project folder and other way is to parse JSON from URL .

iOS Swift JSON Parsing Tutorial, JSON Parsing and decoding in Swift is really easy with the default API. Learn how to convert dates, define custom models and parse JSON  Using Swift Dictionaries we can easily fetch the values from the keys. In this tutorial, we’ll be parsing JSON data from a local resource file. The JSONSerialization class is used to parse a JSON data into a dictionary of key-value pairs by converting the Data object. The type of a JSON data is [String: Any].

JSON Parsing in Swift explained with code examples, swift: Model; Athletes.json: The data source file; TableViewController: Handling table view events; ViewController: Display all information of the  Since the release of Swift 4, Apple introduced the Codable protocol to simplify the whole JSON archival and serialization process. We will also look into this new feature and see how we can apply it in JSON parsing. JSON Demo App. As usual, we’ll create a demo app. Let’s call it KivaLoan.

iOS: How to Read and Update Local JSON file with TableView, If you want to parse JSON by hand rather than using Codable , iOS has a built-in alternative called JSONSerialization and it can convert a  It is much better to use the Codable protocol which along with the decoder allows you to basically map the JSON to related code structures. Here is an example of how you could parse this JSON using the Swift 4 codable protocol (done in a Swift Playground)

How to parse JSON using JSONSerialization, SwiftyJSON is a Swift library for reading and processing JSON data. data most especially JSON files, this is where SwiftyJSON comes in,  We will assume that we want to have a JSON file added inside our project and want to access its data in swift language. Code. You can create a JSON file in Xcode by going to File > New File > Empty and give the file any name (eg. example.json). The file will be added and then we can add a JSON String in the file. i.e. –

  • There is a tutorial here that does a URL request and loads the results in a UITableView
  • I wrote an API fully up to date for Swift 3:
  • For example, let jsonData = NSData.dataWithContentsOfFile(filepath, options: .DataReadingMappedIfSafe, error: nil)
  • The problem with this approach is that you end up with a bunch of foundation objects. Namely NSString, NSNumber, NSArray, NSDictionary, or NSNull. Which creates a heck of a down casting burden if you want to deal with native Swift typed later on in your code. Especially if you have nested dictionaries and arrays. Does anyone know how to deal with this?
  • These types are bridged between Swift and Obj-C.
  • The correct way to load a file in iOS 8.1 seems to be: NSData(contentsOfFile: path). See…:
  • @bubakazouba: Pity I can't downvote a comment. Couple of things: 1. Caroline already provided a snippet for loading data from a file (which is what OP wanted). 2. Your code uses ASCII encoding which loses all unicode symbols, including beyond-English language support.
  • A question regarding your Github repo: how you actually execute the main.swift? I am having trouble executing it from within the playground as you cant seem to refer to classes defined in your own project from the playground (?!) thanks!
  • I've marked methods public in the latest repo. That makes the minimum requirement to Beta4 so don't forget to upgrade Xcode before try
  • Ok thanks, I was really looking for how exactly to execute the example code. I tried playgroung but it didn't work as I was unable to reference the JSON class (its a known issue you cant refer to the classes in your project)
  • I can't make it work :( This time I'm not trying to use it in playground, I've added your json.swift to my project and in another class I'm trying to use it. It does not work. I tried the simplest JSON: { "id": "Janos" }, created the JSON object, called its toString method, it spits out the file contents correctly, however when I call myJson["id"].asString I get nil. What am I missing?
  • I was trying to construct a JSON object passing a String in the constructor... I've changed to how you do in the example now it works a treat. Only question is which one to use now, yours or SwiftyJSon :)
  • could u help me in creating data model with another example @Prine
  • Forgive my ignorance. What are the advantages of using your library over one like SwiftyJSON?