Leverage decodable for personalized JSON parsing

I possess a json in this particular structure:

{  
   "route":{  
      "1":"Natural Attractiveness",
      "2":"Cultural Attractiveness",
      "3":"For Families with Children",
      "5":"For Seniors",
      "6":"For Eagles",
      "8":"Disabled"
   },
   "apartments":{  
      "1":"WiFi",
      "4":"Gastronomy",
      "5":"Parking",
      "6":"For Disabled",
      "7":"For Families with Children",
      "8":"For Seniors"
   },
   "levels":{  
      "1":"Easy",
      "2":"Medium",
      "3":"Difficult",
      "4":"Very Difficult"
   }
}

I am interested in decoding it using a simpler approach, but I am uncertain about how to decode these sub dictionaries. While they are represented as dicts, I believe they should be arrays instead. Is there a way for me to implement something that will allow me to decode it in a unique manner, resulting in arrays? Currently, my code looks like this:

struct PreferencesList: Decodable {

    private enum CodingKeys: String, CodingKey {
        case routes     = "route"
        case apartments
        case levels
    }

    let routes:     [Preference]
    let apartments: [Preference]
    let levels:     [Preference]
}

struct Preference: Decodable {
    let id:   Int
    let name: String
}

Answer №1

Perhaps it would be beneficial to tackle this task in a step-by-step manner.

It is advisable to maintain the structure as it is without requiring Preference to conform to Decodable. Instead, customize the

init(from decoder: Decoder) throws
method as shown below:

init(from decoder: Decoder) throws {
    let container = try decoder.container(keyedBy: CodingKeys.self)
    let routes = try container.decode([String: String].self, forKey: .routes)
    self.routes = []
    for (key, value) in routes {
        self.routes.append(Preference(id: key, name: value))
    }
    // Repeat the process for other variables...
}

This approach may provide some assistance.

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

What is the process for extracting information from JSON data that is not in

Attempting to extract data from a local .json file by utilizing StreamReader and Json.NET. The json content and code snippet are as follows: Contents of .json file: {"rate":50,"information":{"height":70,"ssn":43,"name":"andrew"}} using (v ...

Tips for resolving SyntaxError: Unexpected end of JSON input when attempting to retrieve JSON data in NodeJs

Recently, I embarked on my journey into Backend development. For the past few days, I've been tirelessly attempting to retrieve a response from an API and display it on my HTML page. However, I keep encountering a persistent error while trying to pars ...

Creating a dynamic trio of graphs with HTML5, CSS3, and Vanilla JavaScript

I successfully created a tree graph using HTML5 and CSS3, but currently the nodes are static. I am looking to enhance the graph by making it dynamic. By dynamic, I mean that if the number of nodes increases or there are multiple children added, the graph ...

Retrieve the unique identifier of a single post from a JSON file within a NuxtJS project

Is there a way to retrieve the unique post id data from a JSON file in NuxtJS? created() { this.fetchProductData() }, methods: { fetchProductData() { const vueInstance = this this.$axios .get(`/json/products.json`) ...

Issue when deserializing JSON credentials for Google Sheets API in C#

I have been attempting to utilize a service account in order to access the GoogleSheets API, but I am encountering issues with my .json file. Below is the code I am using: try { string[] scopes = new string[] { SheetsService.Scope.Spreads ...

Converting XML into an Array Using PHP

I attempted to parse an XML string using PHP. Here is an example of the XML: <?xml version="1.0"?> <root> <Log> <Item> <name>![CDATA[James]]</name> <address>![CDATA[Korea]]< ...

Invalid parameters passed to JSON_TABLE

I need to extract json data from a row in one of my tables and programmatically select it into another table. Currently, I am only able to do this when I manually provide the raw json data. Here is what I have done so far: SELECT attribute_name, a ...

Decode the JSON serialized format generated by CircularJSON

I have a JSON object in my node.js code that contains circular references. To send this information to the browser, I utilized the NPM package circular-json to stringify the object and serialize the circular references: var CircularJSON = require("circula ...

The WordPress database supports JSON formatting for data storage

I am facing an issue with importing JSON data into a WordPress database. The correct table has been identified, but the example JSON data in the table is not in a standard JSON format. The JSON data I need to import is: {"name": "John","last_name": "Doe"} ...

Node js does not support iteration for DirectoryFiles

I am currently working on a program aimed at mapping all the json files within a specific directory. As I am new to JavaScript, this inquiry may not be ideal or obvious. Here is my code: const fs = require('fs'); const { glob } = require('gl ...

Connection error between frontend and backend was encountered

Whenever I try to register on my page and connect it to the database, I encounter an error after pressing the sign-in button... "Uncaught (in promise) TypeError: Converting circular structure to JSON --> starting at object with constructor &apo ...

How can one effectively access a nested JSON value in Angular by concatenating all fields?

If we have a JSON stored in the variable person like below: { "firstName": "First Name", "lastName": "Last Name", "address": { "city": "New-York", "street": "Some Street" } } To access the value of street, we would typical ...

Rails JSON output is suddenly causing timestamps to glitch and default to 2000-01-01T01:31:35Z. What could be causing this unexpected

Currently, I am constructing a JSON object in Rails like this: @list = Array.new @list << { :created_at => item.created_at } end @list.to_json The problem arises when the browser receives data like this: "created_at\":\"200 ...

Creating a multi-level JSON object from a string: A step-by-step guide

I've organized my HTML file in the following structure: Chapter 1.1 1.1.1 interesting paragraph 1.1.1.1 interesting paragraph Chapter 1.2 1.2.1 interesting paragraph 1.2.1.1 interesting paragraph ... Chapter 11.4 ... 11.4.12 interesting ...

Transform basic text into nested JSON structure with JavaScript

There is a plain string in my possession which contains various conditions. const optionString = '{2109} AND ({2370} OR {1701} OR {2702}) AND {1234} AND ({2245} OR {2339})'; The goal is to transform this string into an object structured as foll ...

Can one effectively retrieve data from Android SQLite database by querying JSON information?

Can Android SQLite databases be queried for JSON data, similar to how XML data can be stored and queried in sql-server using xpath? Is it possible to do something like this with sqlite? ...

Utilizing Pushwoosh to Send Push Notifications via VB.net and JSON

I'm currently trying to send a message to a device using the Pushwoosh API through my VB.Net application with a premium account. The code seems to be working fine, but I keep receiving a 400 error code from the server. Any suggestions on what might be ...

Obtain sub-elements from deeply nested JSON structures

I have a JSON string with the following structure: "total": 5, "filtered": 5, "items": [ { "assignedProducts": [ "antivirus" ], "cloned": false, "device_encryption_status_unmanaged": false, "java_id": "2408cf5b-669c-434e-ac4c-a08d93c40e6a" ...

Breaking down and modifying JavaScript JSON objects

Can someone explain how to separate a JSON object and make updates based on the ID? I've heard about using stringify! But how do I actually implement the function to update the object? <input type="text" value="{"id":"1","price":"30.00","edit":0}, ...

Struggling to execute JSON parsing with Klaxon and Anko's doAsync?

I am encountering an issue while attempting to parse a JSON-containing URL upon button click: button.setOnClickListener { doAsync{ val result = URL("http://date.jsontest.com/").readText() val parser ...