Reading in a JSON File Using Swift

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

I'm really struggling with trying to read a JSON file into Swift so I can play around with it. I've spent the best part of 2 days re-searching and trying different methods but no luck as of yet so I have signed up to StackOverFlow to see if anyone can point me in the right direction.....

My JSON file is called test.json and contains the following:

{
  "person":[
     {
       "name": "Bob",
       "age": "16",
       "employed": "No"
     },
     {
       "name": "Vinny",
       "age": "56",
       "employed": "Yes"
     }
  ]
}    

The file is stored in the documents directly and I access it using the following code:

let file = "test.json"
let dirs : String[] = NSSearchPathForDirectoriesInDomains(
                                                          NSSearchpathDirectory.DocumentDirectory,
                                                          NSSearchPathDomainMask.AllDomainMask,
                                                          true) as String[]

if (dirs != nil) {
    let directories: String[] = dirs
    let dir = directories[0]
    let path = dir.stringByAppendingPathComponent(file)
}

var jsonData = NSData(contentsOfFile:path, options: nil, error: nil)
println("jsonData \(jsonData)" // This prints what looks to be JSON encoded data.

var jsonDict = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: nil) as? NSDictionary

println("jsonDict \(jsonDict)") - This prints nil..... 

If anyone can just give me a push in the right direction on how I can de-serialize the JSON file and put it in an accessible Swift object I will be eternally grateful!

Kind Regards,

Krivvenz.

Follow the below code :

if let path = NSBundle.mainBundle().pathForResource("test", ofType: "json")
{
    if let jsonData = NSData(contentsOfFile: path, options: .DataReadingMappedIfSafe, error: nil)
    {
        if let jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers, error: nil) as? NSDictionary
        {
            if let persons : NSArray = jsonResult["person"] as? NSArray
            {
                // Do stuff
            }
        }
     }
}

The array "persons" will contain all data for key person. Iterate throughs to fetch it.

Swift 4.0:
if let path = Bundle.main.path(forResource: "test", ofType: "json") {
    do {
          let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
          let jsonResult = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves)
          if let jsonResult = jsonResult as? Dictionary<String, AnyObject>, let person = jsonResult["person"] as? [Any] {
                    // do stuff
          }
      } catch {
           // handle error
      }
}

Read JSON file with Swift 3, Your problem here is that you force unwrap the values and in case of an error you can't know where it comes from. Instead, you should handle  JSON stands for JavaScript Object Notation and is a minimal, readable format for structuring data. It is used to transmit data between a server and web application, as an alternative to XML.JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is super-easy for humans to read and write. It is easy for machines to parse

If anyone is looking for SwiftyJSON Answer: Update: For Swift 3/4:

if let path = Bundle.main.path(forResource: "assets/test", ofType: "json") {
    do {
        let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .alwaysMapped)
        let jsonObj = try JSON(data: data)
        print("jsonData:\(jsonObj)")
    } catch let error {
        print("parse error: \(error.localizedDescription)")
    }
} else {
    print("Invalid filename/path.")
}

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  how - Reading in a JSON File Using Swift swift json parsing example (14) Swift 3.0, Xcode 8, iOS 10

Swift 4 using Decodable

struct ResponseData: Decodable {
    var person: [Person]
}
struct Person : Decodable {
    var name: String
    var age: String
    var employed: String
}

func loadJson(filename fileName: String) -> [Person]? {
    if let url = Bundle.main.url(forResource: fileName, withExtension: "json") {
        do {
            let data = try Data(contentsOf: url)
            let decoder = JSONDecoder()
            let jsonData = try decoder.decode(ResponseData.self, from: data)
            return jsonData.person
        } catch {
            print("error:\(error)")
        }
    }
    return nil
}

Swift 3

func loadJson(filename fileName: String) -> [String: AnyObject]? {
    if let url = Bundle.main.url(forResource: fileName, withExtension: "json") {
        do {
            let data = try Data(contentsOf: url)
            let object = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
            if let dictionary = object as? [String: AnyObject] {
                return dictionary
            }
        } catch {
            print("Error!! Unable to parse  \(fileName).json")
        }
    }
    return nil
}

iOS: How to Read and Update Local JSON file with TableView, swift: Model; Athletes.json: The data source file; TableViewController: Handling table view events; ViewController: Display all information of the  Reading in a JSON File Using Swift,How to parse JSON data from local JSON File swift 3,Swift Read .JSON file from XCode bundle,How to get data from local JSON file in swift,Read JSON file with Swift iOS

Xcode 8 Swift 3 read json from file update:

    if let path = Bundle.main.path(forResource: "userDatabseFakeData", ofType: "json") {
        do {
            let jsonData = try NSData(contentsOfFile: path, options: NSData.ReadingOptions.mappedIfSafe)
            do {
                let jsonResult: NSDictionary = try JSONSerialization.jsonObject(with: jsonData as Data, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary
                if let people : [NSDictionary] = jsonResult["person"] as? [NSDictionary] {
                    for person: NSDictionary in people {
                        for (name,value) in person {
                            print("\(name) , \(value)")
                        }
                    }
                }
            } catch {}
        } catch {}
    }

Parse JSON from file and URL with Swift, 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. Step 2: Create the Codeable Struct. Now that we have our data. Step 3: Read the local file. Step 4: Create the JSON Parse method. Step 5: Create read JSON from URL method. Step We often use JSON to send and receive data from web services. We can do this easily with Swift. Most applications are fully based on JSON. If your application communicates with a web-service

Updated names for Swift 3.0

Based on Abhishek's answer and Druva's answer

func loadJson(forFilename fileName: String) -> NSDictionary? {

    if let url = Bundle.main.url(forResource: fileName, withExtension: "json") {
        if let data = NSData(contentsOf: url) {
            do {
                let dictionary = try JSONSerialization.jsonObject(with: data as Data, options: .allowFragments) as? NSDictionary

                return dictionary
            } catch {
                print("Error!! Unable to parse  \(fileName).json")
            }
        }
        print("Error!! Unable to load  \(fileName).json")
    }

    return nil
}

How to Parse JSON from File & URL (in swift 4.2), JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is super-easy for humans to read and write. It is easy for machines  Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information. Learn more . Writing a SwiftUI model to read from a JSON file with Arrays. Ask Question Asked 6 months ago. Active 6 months ago. Viewed 662 times

iOS Swift JSON Parsing Tutorial, 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  You supply a sample JSON object with a class name and the tool will generate a corresponding Swift class, as well as any needed subsidiary Swift classes, to represent the structure implied by the sample JSON. Also included are class methods used to populate Swift objects, including one that utilizes the NSJSONSerialization.JSONObjectWithData method. The necessary mappings from the NSArray and

JSON Parsing in Swift explained with code examples, JSON Parsing and decoding in Swift is really easy with the default API. Learn how to convert dates, define custom models and parse JSON  JSON is the most commonly used format to send and receive data from the web services. The data is in the form of key-value pairs. 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.

How to Parse JSON in Swift 5, will learn how to parse JSON for iOS and macOS apps using Swift 5. to learn the basics Duration: 21:51 Posted: Apr 26, 2019 You can use the Foundation framework’s JSONSerialization class to convert JSON into Swift data types like Dictionary, Array, String, Number, and Bool. However, because you can’t be sure of the structure or values of JSON your app receives, it can be challenging to deserialize model objects correctly.

Comments
  • use the error parameter...
  • Please post actual, compilable code. As it is now, path is visible only in if scope, and unresolved when you use it in NSData(contentsOfFile, options, error); you also have typos in enum names.
  • My API is fully updated for Swift 3: github.com/borchero/WebParsing
  • this is key -> "values": "%LOAD VALUE FROM tmclass.json file%" and i need to parse another JSON from file then how i can achieve this in SWIFT ?
  • It would be more helpful if you explained why/how this solves the problem described in the question, instead of just presenting a bunch of code.
  • Hi Abhishek - Thanks for your answer but it still doesn't work. That causes the application to crash with the below error: 2014-06-25 16:02:04.146 H & S Capture[4937:131932] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[_NSPlaceholderData initWithContentsOfFile:options:error:]: nil file argument' *** First throw call stack: Any ideas on why this is? For the jsonData options: I put (path, options: NSDataReadingOptions.DataReadingMappedIfSafe, error: nil)
  • Your file path is not correct. Acually, there is no file named test.json at the path specified by you. Please check for the correct location of the file
  • "let jsonData = NSData(contentsOfFile:path!)" instead of "let jsonData = NSData.dataWithContentsOfFile(path, options: .DataReadingMappedIfSafe, error: nil)"
  • It's better to use guard else statements here instead of this pyramid of doom though.
  • this turned me onto swiftyJSON and carthage! thanks :)
  • i used it only to discover it lacks object mapping , i will try a different library next time