Navigating the intricacies of parsing JSON data in SwiftyJSON can be a

I'm utilizing SwiftyJSON.

This is an example of a json string:

{
   "geocoded_waypoints" : [
      {
         "geocoder_status" : "OK",
         "place_id" : "ChIJkcemZ9r9jT8RCoy7cipVk3Q",
         "types" : [ "route" ]
      },
      {
         "geocoder_status" : "OK",
         "place_id" : "ChIJzYyVGtcFjj8RMoV0IaoNhzA",
         "types" : [ "route" ]
      }
   ],
   "routes" : [
      {
         "bounds" : {
            "northeast" : {
               "lat" : 35.7884236,
               "lng" : 51.43490389999999
            },
            "southwest" : {
               "lat" : 35.7056256,
               "lng" : 51.3073962
            }
         },
         "copyrights" : "Map data ©2017 Google",
         "legs" : [
            {
               "distance" : {
                  "text" : "20.9 km",
                  "value" : 20893
               },
               "duration" : {
                  "text" : "32 mins",
                  "value" : 1936
               },
               "end_address" : "Tehran Province, Tehran, Hossein, Iran",
               "end_location" : {
                  "lat" : 35.7883586,
                  "lng" : 51.43490389999999
               },
               "start_address" : "Tehran Province, Tehran, Kooy-e-Bimeh, Rostam, Iran",
               "start_location" : {
                  "lat" : 35.7056307,
                  "lng" : 51.3167437
               },
               "steps" : [
                  {
                     "distance" : {
                        "text" : "59 m",
                        "value" : 59
                     },
                     "duration" : {
                        "text" : "1 min",
                        "value" : 21
                     },
                     "end_location" : {
                        "lat" : 35.70562779999999,
                        "lng" : 51.31739839999999
                     },
                     "html_instructions" : "Head \u003cb\u003eeast\u003c/b\u003e on \u003cb\u003eRostam\u...
                     
                  
        
        ......
        

            print("--->\(json["routes"]["legs"]["distance"]["text"].string)")


        }

The desired output is

routes->legs->distance->text
.

Codes used:

   let json = NSString(data: data, encoding: String.Encoding.utf8.rawValue) as! String
        if let data = json.data(using: String.Encoding.utf8) {
            let json = JSON(data: data)

            print("--->\(json["routes"]["legs"]["distance"]["text"].string)")


        }

print returns --->nil.

Answer №1

The variables <code>routes and legs are both arrays, make sure to retrieve the first entry initially:

let json = NSString(data: data, encoding: String.Encoding.utf8.rawValue) as! String
if let data = json.data(using: String.Encoding.utf8) {
    let json = JSON(data: data)
    if let route = json["routes"].first {
        if let leg = route["legs"].first {
            print("--->\(leg["distance"]["text"].string)")
        }
    }
}

p.s. It is advisable to implement some logic checks in case you do not require the first entries from the arrays.

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

Adding parameters to TR or TDs in DataTables 1.10.5 via Ajax: A step-by-step guide

My goal is to dynamically load datatable data using AJAX and customize the rows and cells by adding parameters such as classes or 'data' attributes. The challenge lies in utilizing a PHP helper that generates JavaScript code, as shown below: $da ...

Unexpected issue with Typo3 v9 - receiving empty Ajax Plugin JSON response

Consider the following setup in TYPO3 for an ajax request: ajaxAutocomplte_page = PAGE ajaxAutocomplte_page { typeNum = 111871 10 = COA_INT 10 { userFunc = TYPO3\CMS\Extbase\Core\Bootstrap->run extensionNa ...

Discover the method for generating five unique objects using data from ten records

I currently have 10 different entries stored in my database table. id value ------------ 1 record-1 2 record-2 3 record-3 4 record-4 5 record-5 6 record-6 7 record-7 8 record-8 9 record-9 10 record-10 M ...

Converting a JSON multidimensional array into a Java multidimensional array

Struggling to convert a JSONArray with a complex multi-dimensional String format into a Java multi-dimensional array. Despite numerous attempted solutions, I keep hitting roadblocks. Hoping for some guidance and clarity from the community. Converting it to ...

A straightforward method to flatten and unflatten JSON files

I've managed to flatten JSON files effortlessly by executing this command in a combination of Node.js and Bash: npx flat foo.json > bar-flat-output.json. But now, I'm searching for another foolproof command that can easily undo the flattening ...

How can I distinguish between a decimal and a long numeric token when using a custom JsonConverter with Utf8JsonReader?

I am working with a json converter that needs to convert a given property value to either a decimal or a long, depending on the type of value. However, I am facing an issue where I cannot determine if the property value is a decimal or a long since the t ...

Having trouble troubleshooting C++ code in Visual Studio Code

Recently, I downloaded Visual Studio Code v1.7.1 to work on my c++ coding assignments for my degree program. While my programming skills are at a basic level, I am quite impressed with VS Code, except for one thing - I have no clue how to debug or build my ...

The error message displayed in Andriod Studio states that there is an issue converting the value "<br" of type java.lang.String to a JSONObject,

I am currently in the process of developing an android app using Android Studio that involves sending data from a User Registration activity to a database. The goal is for the user to input all the required information, click the register button, and have ...

Decoding JSON Data in Angular 2

I am facing a challenge where I have an array of JSON objects that need to be parsed into my Tournament class. The Tournament class has the following structure: export class Tournament { constructor (public id: number, public name: string, ...

Extracting meta header information in JSON format from Rank Math plugin: A step-by-step guide

I've been working with the Rank Math plugin and I'm looking to extract the meta header information in JSON format. Can you assist me with this? Currently, the Rank Math plugin provides the meta head data in HTML form, but I need it to be display ...

Utilizing Jackson JsonSerializer with the @ResponseBody annotation in Spring for an enum interface

Similar inquiries Spring @ResponseBody Jackson JsonSerializer with JodaTime Usage of @JsonSerialize and JsonSerializer The Issue at Hand In my code, there is an enum defined as follows: @JsonSerialize(using = JSONI18NSerializer.class) public enum Stat ...

What is the proper way to execute this API request and retrieve the latest news data using the Fetch method?

Note: Please note that the API Key used in this code is not a real one for privacy reasons. const url = 'http://newsapi.org/v2/everything?' + 'q=platformer&' + 'apiKey=3ce15c4d1fd3485cbcf17879bab498db'; ...

What is the best way to combine these two arrays in order to generate the desired JSON structure in a React

Is there a way to transform two arrays like these: const age = [31,53,62] const names = ['john', 'sam', 'kathy'] Into the structure shown below: const data = { "children": [ { "id": 1, "name": "john", "age ...

What is the best way to send an Ajax Json Response to a php script?

My current setup involves an Ajax call using the xmlHttpRequest to retrieve data from a server. I aim to format this response into a specific string and share it on a different server. To achieve my goal, I am leveraging a php script for processing the fo ...

How can I easily send JSON using PhpStorm/WebStorm REST client?

Within the PhpStorm / WebStorm version of 2017, there exists a REST client that allows us to send requests and analyze responses. Typically, when I send a POST request using the easy form in the UI to create request parameters, the parameters are formatte ...

Extract only the values from a JSON string using Regular Expressions

Need help cutting out specific values from a JSON String in Flutter/Dart. Here's an example of the JSON String: [{"insert":"Test12\n"},{"insert":"Test1","attributes":{"b":true}},{&quo ...

Tips for verifying elements using the Loop technique in a JSON array

I am new to JavaScript and I have been trying to run the following code with an expected result like this: [["00:04:12","05:54:46"],["06:06:42","12:45:22"],["12:51:11","15:56:11"]] However, my script is not working as expected. Can someone please help ...

Create a loop to iterate through dates within a specified range using the Fetch API

When I need to get the exchange rate from the bank for a specific interval specified in the input, I follow these steps. The interval is defined as [startdate; enddate]. However, in order to make a successful request to the bank, the selected dates must be ...

What are some effective techniques for leveraging ElasticSearch's term queries in order to refine results by searching for a specific value within an array

I'm trying to make a POST request to an API in order to receive only the hits with the role "editor". The initial response, without any filters, appears as follows: _source: { configuration: { roles : [ {role : "lead"}, {role ...

Loading JSON data into an ExtJS combo box

I am having JSON data: {"total":100, "category": [Village, City, School, HighSchool]} for an ExtJS combobox: reader: new Ext.data.JsonReader({ root: 'category'}, [{name: 'category'}]) The data is not loading in the combobox. When I ...