Unlocking JSON with various structures using Swift

I am dealing with json data that follows a consistent structure from a nosql database (PK, SK, attributes). The content of the attributes section varies depending on the value of SK.

For instance:

[
  {
    "PK": "POLL#1544693DF0E88EC-3225-410E-B156-D13781B238F6",
    "SK": "#METADATA#1544693DF0E88EC-3225-410E-B156-D13781B238F6",
    "attributes": {
      "latitude": "53.34589121858683",
      "longitude": "-6.272215191675388",
      "max_choices": 50,
      "number": "1544693",
      "poll_open": false,
    }
  },
  {
    "PK": "POLL#1544693DF0E88EC-3225-410E-B156-D13781B238F6",
    "SK": "CHOICE#00a6ec5c-acc1-40f1-a087-31160d2cfc65",
    "attributes": {
      "distance": 790.95097525,
      "latitude": 53.3416,
      "price": "€€",
      "categories": [
        {
          "title": "Ramen",
          "alias": "ramen"
        }
      ],
      "vote_count": 0,
      "longitude": -6.26274
    }
  }
]

I am facing challenges trying to decode this without encountering errors. I have spent hours stuck on this problem.

I have set up the following struct:

struct Result: Codable {
    var PK: String
    var SK: String
    var attributes: String
}

However, when I attempt to decode, I receive the error message:

typeMismatch(Swift.String, Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue: "attributes", intValue: nil)], debugDescription: "Expected to decode String but found a dictionary instead.", underlyingError: nil))

All I want is to decode 'attributes' as a generic string and then parse it later based on the value of SK once I figure out how to properly handle it. Why does this seem so complex?

Answer №1

Are you currently in need of specific attributes, or are you solely interested in the primary key (PK) and sort key (SK)? If you don't require it, simply omit

var attributes: String

it from your struct. This will prevent a decoding error, allowing the successful decoding of the other two parameters, albeit without the attributes data. Since Swift cannot handle attributes as a string due to its dictionary-like nature, proper struct definition is crucial. You could approach this by defining nested structs like so:

struct Result: Codable {
var PK: String
var SK: String
var attributes: Attributes
}

struct Attributes: Codable {
var latitude: String
var longitude: String
// add any other expected attributes here
}

The important thing is to only include attributes that you know will be present; otherwise, an error may occur.

Answer №2

To properly handle this scenario, you should utilize JSONSerialization instead of Codable. If you prefer to stick with the same struct, make the following adjustments:

struct Result {
    var primaryKey: String
    var secondaryKey: String
    var attributes: [String: Any]
}

Then, proceed to decode the JSON data as shown below:

var result: Result?
do {
    if let jsonDict = try JSONSerialization.jsonObject(with: data) as? [String: Any],
       let pk = jsonDict["primaryKey"] as? String,
       let sk = jsonDict["secondaryKey"] as? String,
       let attributes = jsonDict["attributes"] as? [String: Any] {
        result = Result(primaryKey: pk, secondaryKey: sk, attributes: attributes)
    }
} catch {
    print(error)
}

Further refinement may be needed for the "attributes" property in Result to enhance its usability, but that is a separate matter.

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

Error occurred: Attempting to retrieve data from API, but encountered an issue with string indices requiring

I am trying to extract specific data from an API's database: import urllib2 import json import csv c = csv.writer(open("analysis output.csv", "wb")) urlIncomeStatement = 'http://dev.c0l.in:5984/income_statements/_all_docs' apiIncomeStatem ...

Obtaining quotations around variables in Flutter JSON: A step-by-step guide

I'm currently utilizing Flutter to transmit JSON headers to my NodeJS server. My objective is to send an email along with a token. However, it seems there's an issue with the code I've implemented. String authuser = '{"email" ...

Troubles encountered while attempting to collapse JSON data in Spark

Attempting to grasp the usage of Spark for processing JSON data, I have come across a rather straightforward JSON file structured as follows: {"key": { "defaultWeights":"1" }, "measures": { "m1":-0.01, "m2":-0.5.....}} After importing this file into a Sp ...

Having trouble deciphering the JSON data structure in JavaScript

How can values be passed back to a form that was submitted to the server using Ajax? In this view (shown below), a simple data structure is returned for testing purposes: def detail(request, widget_id): widget = get_object_or_404(Widget, pk=widget_i ...

Exploring the Methods to Filter JSON Data in Node.js

There have been significant changes in technologies over the past couple of years since I last checked answers to this question. Currently, I am dealing with JSON files that are being transmitted from a database to my server. My main concern is how to eff ...

The size of the .json file exceeds the limit for opening in R using rjson

I'm facing a data challenge with a hefty 5.1 GB json file that I'm struggling to read in R using rjson. My ultimate goal is to create a dataframe from it, but the sheer size seems to be causing obstacles in loading it successfully. Do any of you ...

I have a json file that I need to convert to a csv format

I am currently working with a json file, but I need to switch it out for a csv file. Do I have to use a specific library to accomplish this task, or can I simply modify the jQuery 'get' request from json to csv? I attempted the latter approach, b ...

Using the typeahead feature to retrieve a value and then incorporating it into an ajax

Currently, I am utilizing the jQuery typeahead plugin for ajax search functionality. In the provided demo, all the data sources are linked to a json file and retrieved from there. However, in my scenario, I am using a php file as the data source. Within ...

How can I convert an Array into a Dictionary using JavaScript?

Is there a clever method (perhaps using a map function) to restructure my data object from this: [ {id: 1, from: "1/1/2021", to: "1/2/2022"}, {id: 2, from: "1/3/2021", to: "1/4/2022"}, {id: 1, from: "1/5/2 ...

I'm trying to wrap my head around Ruby's "super" keyword in the scenario of super(options.merge(include: :comments)). Can you help explain

When combining AngularJS with RoR, I have come across examples of using code similar to the following in model files: def as_json(options = {}) super(options.merge(include: :comments)) end My understanding is that this code allows the JSON object ...

The issue encountered is: Error [ERR_PACKAGE_PATH_NOT_EXPORTED]. The specific subpath 'lib/sync' within the package is not properly defined by the "exports" section in the package.json file located in the node_modules/csv-parse

Every time I execute index.js in Node.js, I encounter this error message. Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: Package subpath './lib/sync' is not defined by "exports" in D:\Scuola\5f_Informatca\Tpsit\Telegram\node_modu ...

How can I retrieve the value of a particular key within a string using Swift?

After receiving a server response, I'm trying to access specific data within it. ( { agreementId = "token.virtual.4321"; city = AMSTERDAM; displayCommonName = "bunch-of-alphanumeric"; displaySoftwareVersion = "qb2/ene/2.7.14"; ...

Having trouble parsing a basic JSON file in Extjs's treepanel widget

I am facing an issue with loading a simple JSON file where nodes are nested inside the "data" attribute as shown below. My expectation is to retrieve two nodes with text AAA and BBB, but instead, I am getting a tree structure with empty nodes that have inf ...

Serializing and deserializing Tuples with Jackson in Scala using JSON

Here, I am attempting to perform a round-trip operation on a Tuple2 using the jackson-module-scala library in Scala 2.10.4. However, it seems that the serializer encodes the Tuple2 as a JSON array, leading to issues with deserialization. Why does this ha ...

Leverage the power of JSON objects in C# programming

I am receiving a JSON response from this web service. Can you provide guidance on how to use this message as an object in my ASP.NET web application? ...

Key within square brackets in a JSON array

I am dealing with a JSON array that includes a square bracket in the key, like this: { "msg":"OK", "data":[ { "nls!type":"NCR", "current":"Assign", "physicalid":"0FFE0001000009FC5BD6805C00001352", "attribute[custTitle]":"Tit ...

Encountering a JSONDecodeError while attempting to save data to a JSON file

I am faced with a JSON file where each entry is accompanied by a corresponding list structure. Here is an example of how the data is structured: { "/home/onur/PycharmProjects/file-tagging/data/world_building_budget.txt": [], "/home/o ...

Utilize jQuery to append YQL output in JSON format to specific IDs in your code

I have a YQL output JSON string at this URL: Check out the YQL JSON here I encountered some other I am exploring why I am facing difficulties in extracting certain items from the returned JSON. For instance, when using jQuery to access the H1 tag within ...

What is the best way to link JSON array information to the HTML using MVC?

I'm currently working with MVC5 and I am trying to populate a div element with data using the .html(data) method. .done(function (data) { var result = $.parseJSON(data); $("#mydata").html(result); }); <div id="mydata"></div> Th ...

Unable to retrieve array contents when utilizing a BLOB in the database

My JSON and PHP setup was able to display my database content smoothly. However, things took a turn when I introduced a blob value for storing images in the database. Now, whenever I run the page, the data fails to display as intended. Below is the code I ...