Interested in learning how to extract an array from a description in Swift 4?

Currently delving into Swift 4, I've come across an algorithm that generates the base 64 representation of an array, as shown below:

extension String {

    func fromBase64() -> String? {
        guard let data = Data(base64Encoded: self) else {
            return nil
        }

        return String(data: data, encoding: .utf8)
    }

    func toBase64() -> String {
        return Data(self.utf8).base64EncodedString()
    }
}
let output = [1, 2, 4, 65].description.toBase64()
print(output.fromBase64()) // "[1, 2, 4, 65]"

The challenge now lies in extracting the array back as an Array, rather than a String. Despite my efforts in researching online resources, parsing methods for this particular type of array have proven elusive (most discussions revolve around JSON parsing).

Answer №1

It is not recommended to depend on the description method for generating a specific output consistently; it is advisable to use a JSON encoder instead (as demonstrated below).

However, it should be noted that "[1, 2, 4, 65]" is a valid JSON array, and a JSON decoder can successfully parse it into an integer array:

let output = "[1, 2, 4, 65]"
do {
    let array = try JSONDecoder().decode([Int].self, from: Data(output.utf8))
    print(array) // [1, 2, 4, 65]
} catch {
    print("Invalid input", error.localizedDescription)
}

Below is a comprehensive example illustrating how you can accurately encode and decode an array of integers to/from a Base64 encoded string.

// Encoding:
let intArray = [1, 2, 4, 65]
let output = try! JSONEncoder().encode(intArray).base64EncodedString()
print(output) // WzEsMiw0LDY1XQ==

// Decoding:
let output = "WzEsMiw0LDY1XQ=="
if let data = Data(base64Encoded: output),
    let array = try? JSONDecoder().decode([Int].self, from: data) {
    print(array) // [1, 2, 4, 65]
} else {
    print("Invalid input")
}

Answer №2

If you're looking to transform a string into an array of integers, consider using the following method:

let encodedString = original.encodeBase64() //"[8, 14, 36, 92]"
if let str = encodedString {
    let charactersToStrip = CharacterSet(charactersIn: ",][ ")
    let separatedValues = str.components(separatedBy: charactersToStrip).filter { $0 != "" }.flatMap { Int($0)}
    print(separatedValues) //[8, 14, 36, 92]
}

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

Utilizing JSON Data with Angular

Currently, I am in the process of developing an AngularJS client that communicates with a REST API running on NodeJS. To retrieve data, I make GET requests by accessing specific URLs with stock symbols appended, such as localhost:8080/stocks/aapl for Apple ...

Using Node.js to return JSON data containing base64 encoded images

In my database, I store all images as base64 with additional data (creation date, likes, owner, etc). I would like to create a /pictures GET endpoint that returns a JSON object containing the image data, for example: Image Data [{ "creation": 1479567 ...

Reorganize child JSON objects into a new object that includes a parent ID

Exploring the realm of JavaScript, I am currently delving into Node.JS to interact with an API and save the data in a SQL Server. Utilizing the "request" and "mssql" Node packages for this task as they possess robust documentation and support. My query re ...

Error: Header settings cannot be changed once they have been sent to the client

After attempting to hit the signup route, I noticed that "req.body" is not capturing any of the POST values. Strangely enough, when testing the same code on Postman using the raw body method, the values are displayed perfectly. const router = require(&apo ...

I encountered a ReferenceError stating that the variable "html" is not defined

Recently, I delved into the world of Node.js for the first time. During my attempt to connect my index.html file, an error message stating 'ReferenceError: html is not defined' popped up. Below is the code snippet from my index.js: var http = re ...

Error encountered while trying to retrieve the response

Currently, I am in the process of developing a script that utilizes node.js, fbgraph API, and the express framework. My task involves sending the user's access_token from an index.html page to the nodejs server via a POST request. I have successfully ...

Tips for isolating the month values from the res.body.results array of objects with the help of JS Array map()

Looking to adjust the custom code that I have which aims to extract months from a string using regex. It seems like I'm almost there but not quite hitting the mark. When checking the console log, I am getting "undefined" values for key/value pairs and ...

Error: JSON at position 1 is throwing off the syntax in EXPRESS due to an unexpected token "

I'm currently utilizing a REST web service within Express and I am looking to retrieve an object that includes the specified hours. var express = require('express'); var router = express.Router(); /* GET home page. ...

Does the JSON property that exists escape NodeJS's watchful eye?

I recently encountered an unexpected issue with a piece of code that had been functioning flawlessly for weeks. In the request below and snippet of the response: //request let campaignRes = request('POST', reqUrl, campaignOptions); //response ...

Accessing a particular level within a JSON object in Node.js

I'm dealing with a two level JSON structure {"Policy": { "Channel": "online", "Credit Score": "20000", "Car": [{ "Age": "28", ...

Transforming JSON data in a Node.js API using JSONata

In need of developing a Node.js REST API for transforming JSON to JSON format. After researching multiple libraries, I have narrowed down my options to "JSONata". You can find a simple sample of JSONata here. The main challenge lies in the fact that the ...

Converting basic text into JSON using Node.js

Today I am trying to convert a text into JSON data. For example: 1 kokoa#0368's Discord Profile Avatar kokoa#0000 826 2 Azzky 陈东晓#7475's Discord Profile Avatar Azzky 陈东晓#0000 703 3 StarKleey 帅哥#6163's Di ...

Transform the results of a database query into JSON format using Node.js

Below is the code snippet I have written: oracledb.getConnection( { user : "user", password : "password", connectString : "gtmachine:1521/sde1" }, function(err, connection) { if (err) { console.error(err); return; } ...

JavaScript library called "Error: JSON input ended unexpectedly"

I am currently operating a server using node.js and Express v4.0 Additionally, I am utilizing the request library. However, when receiving a response from the server, I encounter an Uncaught SyntaxError: Unexpected end of JSON input. The response I receiv ...

Encountered a SyntaxError on JSON Web Tokens Node JS Server: Unexpected token } found in JSON at position 24

Me, along with others, have encountered this issue: SyntaxError: Unexpected token } in JSON at position 24 at JSON.parse (<anonymous>) while following a tutorial on JSON Web Tokens (TUTORIAL LINK: https://www.youtube.com/watch?v=mbsmsi7l3r4&t=34s ...

Troubleshooting issues with the delete functionality in a NodeJS CRUD API

I've been struggling to implement the Delete functionality in my nodejs CRUD API for the past couple of days, but I just can't seem to get it right. As I'm still learning, there might be a small detail that I'm overlooking causing this ...

Reading cached JSON value in a Node.js application

Recently, I embarked on creating a node.js application and reached a stage where I needed to retrieve a value from an updated JSON file. However, my attempts using the 'sleep' module to introduce a small delay were unsuccessful. I'm relativ ...

An array containing numerous "case" triggers

var message = "hello [[xxx]] bye [[ZZZ]]" var result, re = /\[\[(.*?)\]\]/g; while ((result = re.exec(message)) != null) { switch (result[1].toLowerCase()) { case "xxx": console.log("found xxx"); br ...

Why is my custom function failing to operate on an array?

My function is created to organize and remove duplicates from a provided array. Below is an excerpt of the code: Bubble Sort - function organize(postsCollection, type, direction){ let target = postsCollection[0][type]; let swapp = false, ...

The NodeJS expressJs Server is unable to receive JSON data

Here is how my ajax request is structured: $.ajax({ url: baseURL, type: 'POST', data: JSON.stringify(sendData), contentType: 'application/json; charset=utf-8', dataType: 'json', async: false, succe ...