Finding the Index of Parsed JSON Data in Swift

I'm struggling with creating a loop to check if an employee can perform a specific service. It seems that the code I wrote for accessing the employee's services is not working. The employee data is loaded as JSON into EmployeesData. I believe I need to get the index from EmployeesData, but I am unsure how to do it with ForEach.

ForEach(EmployeesData){ employee in
  //This does not work
  if(employee.services[0] == "service")
}


struct Employees: Codable, Identifiable{
  var id: UUID
  var firstname: String
  var lastname: String
  var services: [String]
  var workingStatus: String
}

//Store employee data in EmployeesData
let EmployeesData: [Employees] = load("Employees.json")

private func load<T: Decodable>(_ filename: String) -> T {
let data: Data

guard let file = Bundle.main.url(forResource: filename, withExtension: nil)
    else {
        fatalError("Couldn't find \(filename) in main bundle.")
}

do {
    data = try Data(contentsOf: file)
} catch {
    fatalError("Couldn't load \(filename) from main bundle:\n\(error)")
}

do {
    let decoder = JSONDecoder()
    return try decoder.decode(T.self, from: data)
} catch {
    fatalError("Couldn't parse \(filename) as \(T.self):\n\(error)")
}
}

Answer №1

if employee.services contains service

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

Encountering an issue when attempting to access a string offset while creating a JSON object in PHP

After countless attempts and failed solutions, I find myself struggling to make this work. The scenario is as follows: I have an initially empty file named contact.json. If the file is empty, I need to add JSON data to it. If it already contains data, I ...

Each iteration transforms the PHP array of associative arrays

During my coding process, I encountered an issue while trying to create an array of periods (each with a start and end time) within a loop using the add() function on temporal variables. The problem is that every time I call add(), all values in the final ...

Retrieving intricate JSON data from a specific web address

I need assistance in extracting and printing the date value from the JSON content available at the specified URL. Specifically, I am looking to retrieve the date value of "data.content.containers.container.locationDateTime" only if the "data.content.conta ...

gather remarks published by a Facebook Page

Is there a way to retrieve the comments made by a Facebook page, such as this one? The code provided only fetches general information. What format should the URL be to retrieve the comments specifically? $Page_ID = 'https://www.facebook.com/nauhote ...

Difficulty arise when AJAX array interacts with MySQL database table

One of the challenges I'm facing on my website involves a series of buttons that correspond to specific table columns in a MySQL database. Both the button IDs and column names are identical. My goal is to gather these IDs into an array, then use AJAX ...

Using PHP to create a NULL value in a .JSON file

After encountering a NULL value in my .json file when trying to write an array to it, I am puzzled as to why this issue only arises with the 'array_push' line after creating a new file. Interestingly, if there is already a .json file present with ...

I have received a JSON multi-line string after entering information in a textarea

I've been working on a small social network project where users can create and share posts. However, I encountered an issue with formatting when storing and displaying the posts. When a user enters text with line breaks in the post creation form, it ...

The command "json_encode($array)" does not seem to be encoding the complete array

I ran a test on the following: <? echo json_encode($array) ?> result: ["PG","Kevin Sad","8000","12"] Upon placing it within a form option value to be selected by my script function: <option value=<? echo json_encode($array) ?> > op ...

Using PHP to iterate over a pair of arrays

When I send data from a web page to a PHP page using Ajax, everything works smoothly. The data is retrieved from $_POST, where I iterate through the values and create an array called checklist. if($_POST != ''): $dataset = $_POST['dat ...

Choose a SQL Statement Based on Conditions

My task involves sending Thank You Messages by posting data to a specific URL. The information I need is retrieved from a table named readtextfilejson, where details of users are stored for sending the messages. The challenge I am facing is in selecting o ...

Searching for multiple lines of text within a PHP document

Recently, I have been working on a project that involves an addon making modifications to a crucial system file. As part of this task, I have created a method to locate specific strings within the file: /** * @param $fileName * @param $str ...

Having trouble parsing JSON data from $_POST while utilizing AngularJS

While working in Angular, I encountered the following scenario: var data = {}; data['name'] = "test"; data['class'] = "testClass"; $http.post('http://testURL',data,function(data){ console.log(data); }); Upon inspecting the ...

What is the Best Way to Understand CloudKit Error Messages?

I'm currently working on a php script that aims to create a record in a CloudKit database. However, I keep encountering this error: object(stdClass)#1 (3) { ["uuid"]=> string(36) "c70072a1-fab6-491b-a68f-03b9056223e1" ["serverErrorCode"]=> ...

Guide on obtaining JSON data in an android application through a PHP file?

I am a beginner in Android development and I have recently created a simple data fetching application. However, I am facing an issue where I am only able to retrieve the value of one variable from my PHP file, even though both variables are present in the ...

Is half of your important information disappearing during JSON conversion?

I have a mysql database of countries, containing 250 records that I want to integrate into an Android app. I understand that using PHP is necessary to convert the data into JSON format. Here is my implementation: <?php require_once('connection. ...

Issue with PHP incorrectly encoding JSON when writing to a file

I encountered a problem while working on this task. I used preg_split in PHP to create an array. However, my challenge now is converting it into JSON format. Despite trying several methods, the resulting code appears poorly written and does not seem to be ...

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":" ...

"Utilizing Time Intervals and Asynchronous JavaScript (

My jQuery code is not automatically refreshing. Can anyone help me figure out what's wrong with the following code? I want it to check for any new bids and update the HTML accordingly :) EDIT: function checkBids(){ var id = $('div.auction&a ...

Using PHP, create a menu tree by filtering an array

$this->loadModel('Menu'); $this->loadModel('SubMenu'); $this->loadModel('SubSubMenu'); $options['joins'] = array( array('table' => 'sub_menus', ...

Discover the method for extracting the value from an array that has been transferred from a php script

So here's the situation - I have a text file containing data. The first step is to convert the content of the text file into an array. $lines = file($filename); Next, the data is sent back to the client (the $filename is determined through ajax). ...