Having trouble with parsing JSON data in Swift?

I've been attempting to utilize Swifty JSON for parsing a local file. While I am able to successfully store content in the data variable, I seem to be encountering issues when trying to use JSON from the SwiftJSON framework as it is not storing any content (resulting in a row count of 0). Can someone please point out what mistake I might be making?

import SwiftyJSON
class MainTableViewController: UITableViewController {
    var numberOfRows = 0
    var documentNames = [String]()

    func parseJSON(){
        let path = NSBundle.mainBundle().URLForResource("documents", withExtension: "json")
        let data = NSData(contentsOfURL: path!) as NSData!
        let readableJSON = JSON(data: data)
        
        numberOfRows = readableJSON["Documents"].count
        
        print(numberOfRows)
        
        for i in 1...numberOfRows {
            let doc = "Doc\(i)"
            if let name = readableJSON["Documents"][doc]["name"].string {
                documentNames.append(name)
            }
        }
    }
}

Answer №1

Make sure to verify if the NSData object is empty or not before proceeding.

if let filePath = NSBundle.mainBundle().URLForResource("content", withExtension: "json") {
    if let fileData = NSData(contentsOfURL: filePath) as? NSData {
        let jsonData = JSON(data: fileData)
        // ...
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Getting Ajax response in HTML Unit can be achieved by leveraging its capability to render the HTML content of the web page

My web application responds with JSON data when I make AJAX requests to the server for CRUD operations. This is because I utilize jQuery to handle the data without needing to refresh the page (MVC). When a new entry is created in the system, the server sen ...

Attempting to save an object that references an unsaved transient instance - ensure the transient instance (com.example.model.Salutation) is saved before

I am facing an issue with saving User object containing a reference to the Salutation model class. Even though the Foreign key (salutation_id) in the User table is optional, I am encountering an error when trying to save the User object after merging and f ...

Parsing a diverse JSON array into a variant List<> with the help of Json.NET

I am faced with a JSON-array that holds objects of various types with different properties. The key property, "type," determines the nature of each object within the array. Take a look at an example snippet of my data below: [{ type : "comment" ...

the issue with file_get_contents not effectively sending every parameter

I have recently created my own API to communicate between two servers. One server is requesting data using file_get_contents and passing GET Parameters, while the other server responds with JSON. Everything was working smoothly until I made a request with ...

Tips for retrieving numerical values from JSON paths using Scala

I just received the following response: { "code" : 201, "message" : "Your Quote Id is 353541551" } To extract the number 353541551 from the above response, I attempted to use some basic Scala code snippets. Here's what I tried: .check((status i ...

Exploring REST APIs with SOAP UI Testing

Is it possible to include JSON format parameters in the request payload for a POST request in restful service testing using SOAP UI? ...

Firebase Error: The creator key was not defined, which cannot be passed as undefined in JSON. Instead, use null

Currently, I'm working on a project using angularFire 0.8.2. The project is actually based on thinkster.io's angular-firebase tutorial. However, I've encountered a hurdle when trying to create a custom user profile and access the data within ...

Utilizing Python to extract data from a JSON file

I have been working on reading a JSON file in Python and have run into an issue where some top values are being skipped. I am currently debugging to identify the root cause of this problem. Here is the code snippet: data = json.load(open('pre.txt&apo ...

JavaScript Execution Sequence: Demystifying the Order of Operations

I am struggling to comprehend the order of execution in the following code snippet. It is a portion of a larger script, but it all begins with $( "#select-overlay" ). function findSelectedMap(mapID) { $.getJSON('maps.json', function (json) { ...

Display a JSON encoded array using Jquery

Within an ajax call, I have a single json encoded array set: $var = json_encode($_SESSION['pictures']); The json encoded array is stored in a variable called "array" When I try to display the contents of "array" using alert, I get this respons ...

Using NodeJS to Send JSON Data via HTTP POST Request

Issue with Sending JSON Data via Http Post in NodeJS const http = require('http'); const fs = require('fs'); var options = { hostname: 'www.postcatcher.in', port: 80, path: '/catchers/5531b7faacde130300002495&apo ...

Can the hash of a string be calculated while it already contains that hash?

As I was working today, I found myself attempting to generate a JSON document that looked like this: { 'a' : 1, 'b' : 2, 'hash' : (some hash value), } The challenge I encountered was setting the hash value to be ...

javascript issue with fetching data from URL using the GET method

Here is my attempt to fetch a JSON file from a server using asynchronous JavaScript promises. I am experiencing an issue where the result is undefined when using a specific URL, but it works when I use a different URL. Below is the working code with a dif ...

Choose the DIV element based on its data attribute using JSON

When using each(), my goal is to: Hide all divs where the data-infos.grpid = $jQuery(this).data('infos').grpid Show the next div where data-infos.ordre = $jQuery(this).data('infos').next_ordre I am unsure how to apply a "where" ...

Develop a CSS layout for the specified design

Aiming to achieve a unique layout using dynamic html strings. The challenge arises when transitioning to the second page as the layout does not adjust upward and images cannot be added to the first page. Attempting to implement the following sample code ...

Having trouble sending a HTTP Post request to a Web Service from my Android Application

Working on an application that involves using both GET and POST requests to interact with Web Services. While the GET requests are working smoothly, encountering challenges with the POST requests. Have tried two different approaches in the code implementat ...

Is it possible to implement a wsdl webservice in Phonegap?

Does anyone know the best way to call a wsdl webservice in Phonegap? Any suggestions on source code or tutorials that could be helpful? ...

In the iOS app when the Ionic HTML5 select keypad is opened, a bug causes the view to scroll upwards and create empty space after tapping the tab

I am currently working with Ionic v1 and AngularJS, utilizing ion tabs: <ion-tabs class="tabs-icon-top tabs-color-active-positive"> <!-- Home Tab --> <ion-tab icon-off="ion-home" icon-on="ion-home" href="#/tab/home"> <ion-nav ...

Unraveling JSON data retrieved from a MySQL query

After successfully encoding a MySQL result from PHP into JSON, I am now faced with the task of decoding it using JavaScript. Let's assume that my string returned is: [{"0":"x","1":"z"},{"0":"xs","1":"zz"}] I would appreciate some guidance on how to ...

Implementing array values into a jQuery graph syntax

After json encoding from php, I have an array that contains information on different categories: [{"Type":"Category","Name":"games","TotalClicks":"162"},{"Type":"Category","Name":"apps","TotalClicks":"29"},{"Type":"Category","Name":"music","TotalClicks":" ...