Convert a string encoded array into an object - arrays

So im getting this array in the form of a string from the server with all the coordinates of objects, shown below:
"[[[-0.340254,51.605946],[-0.340278,51.605685],[-0.339718,51.604400],
[-0.339280,51.603746],[-0.338915,51.603454],[-0.338657,51.603018],
[-0.338427,51.601810],[-0.338518,51.600885],[-0.337471,51.599908],
[-0.337378,51.599682],[-0.337456,51.599116],[-0.336860,51.597669],
[-0.335843,51.597043],[-0.335635,51.596816],[-0.335112,51.595720],
[-0.335232,51.594400],[-0.335057,51.593273],[-0.334827,51.592847],
[-0.333187,51.591889],[-0.333236,51.590945],[-0.332894,51.590446],
[-0.332727,51.589868],[-0.332791,51.589320],[-0.332638,51.589156],
[-0.332028,51.587295],[-0.332326,51.585438],[-0.332243,51.585365],
[-0.332292,51.585186],[-0.331651,51.582991],[-0.333713,51.581096],
[-0.334020,51.580570],[-0.334055,51.580013],[-0.337963,51.580123],
[-0.340047,51.579954],[-0.341778,51.579979],[-0.341883,51.579881]]]"
how would i convert this into an array?
Thank you in advance!
so i would want it the form [[Double]]
let objects = [[[-0.340254,51.605946],[-0.340278,51.605685],[-0.339718,51.604400],
[-0.339280,51.603746],[-0.338915,51.603454],[-0.338657,51.603018],
[-0.338427,51.601810],[-0.338518,51.600885],[-0.337471,51.599908],
[-0.337378,51.599682],[-0.337456,51.599116],[-0.336860,51.597669],
[-0.335843,51.597043],[-0.335635,51.596816],[-0.335112,51.595720],
[-0.335232,51.594400],[-0.335057,51.593273],[-0.334827,51.592847],
[-0.333187,51.591889],[-0.333236,51.590945],[-0.332894,51.590446],
[-0.332727,51.589868],[-0.332791,51.589320],[-0.332638,51.589156],
[-0.332028,51.587295],[-0.332326,51.585438],[-0.332243,51.585365],
[-0.332292,51.585186],[-0.331651,51.582991],[-0.333713,51.581096],
[-0.334020,51.580570],[-0.334055,51.580013],[-0.337963,51.580123],
[-0.340047,51.579954],[-0.341778,51.579979],[-0.341883,51.579881]]]
so if i was to do objects[0][0] it should return [-0.340254,51.605946]
func convert(s: String) -> [[[Double]]]{
do{
let array = try NSJSONSerialization.JSONObjectWithData(s.dataUsingEncoding(NSUTF8StringEncoding)!, options: []) as? [[[Double]]]
return array!
}catch{
}
return [[[]]]
}

You simply have a JSON response of a 3D array. I loaded your string into the Swift REPL, and was able to parse it like so:
import Foundation
let s = /* your string */
let array = NSJSONSerialization.JSONObjectWithData(s.dataUsingEncoding(NSUTF8StringEncoding)!, options: []) as? [[[Double]]]
Output
$R3: [[[Double]]]? = 1 value {
[0] = 36 values {
...
Code Sample
func convert(s: String) -> [[[Double]]] {
if let data = s.dataUsingEncoding(NSUTF8StringEncoding),
let object = try? NSJSONSerialization.JSONObjectWithData(data, options: []),
let array = object as? [[[Double]]]
{
return array
}
return [[[]]]
}

Related

Convert Array of Dictionaries into Array of Values from NSFetchRequest

I have a dictionary that is being returned from a NSFetchRequest using the fetchRequest.resultType = .dictionaryResultType the dictionary returned is [Any] and looks like the folowing:
teams [{
team = Canadiens;
}, {
team = "Maple Leafs";
}, {
team = Penguins;
}]
I would like just an array of the values, like this [Canadiens, "Maple Leafs", Penguins"], how can I convert the array of dictionaries into an array only containing the values?
Full fetch
func teamNames(managedContext: NSManagedObjectContext) {
//print("\(self) -> \(#function)")
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Players")
fetchRequest.fetchBatchSize = 8
fetchRequest.propertiesToGroupBy = [#keyPath(Players.team)]
fetchRequest.propertiesToFetch = [#keyPath(Players.team)]
fetchRequest.resultType = .dictionaryResultType
do {
let fetchTeamNamesDictionary = try managedContext.fetch(fetchRequest)
print("fetchTeamNamesDictionary \(fetchTeamNamesDictionary)")
} catch let error as NSError {
print("GoFetch|teamNames: Could not fetch. \(error), \(error.userInfo)")
}
}
Alternate to accepted answer:
do {
let fetchTeamNamesArray = try managedContext.fetch(fetchRequest)
for array in fetchTeamNamesArray {
let teamName = (array as AnyObject).value(forKey: "team") as! String
teamNameArray.append(teamName)
}
As you clearly know that the keys and values of the result are strings force-downcast the result to [[String:String]]
let teamArray = try managedContext.fetch(fetchRequest) as! [[String:String]]
Then map the dictionaries to its value for key team
let teamNames = teamArray.map { $0["team"]! }

how to get array from dictionary in swift 3

I don't understand how to get array from dictionary, i have tried in this code but i want get array only content and type
This is my array
{
wsResponse = {
aarti =(
{
content = "";
identifier = "slok_one";
title = 1;
type = "\U092d\U0915\U094d\U0924\U093e\U092e\U0930";
},
{
content = "";
identifier = "slok_two";
title = 2;
type = "\U092d\U0915\U094d\U0924\U093e\U092e\U0930";
},
{
content = "";
identifier = "slok_three";
title = 3;
type = "\U092d\U0915\U094d\U0924\U093e\U092e\U0930";
}
}
);
};
Here is my code
Alamofire.request(url, method: .get, parameters: nil, encoding: JSONEncoding.default)
.responseJSON { response in
if let status = response.response?.statusCode {
switch(status){
case 201:
print("example success")
default:
print("error with response status: \(status)")
}
}
//to get JSON return value
if let array = response.result.value
{
let JSON = array as! NSDictionary
print("\(JSON)")
let response = JSON["wsResponse"] as! NSDictionary
let data = response["aarti"]
}
}
i want array from this ,like content,title,type
thank you in advance
According to the JSON this prints all values in the aarti array:
if let JSON = response.result.value as? [String:Any] {
if let response = JSON["wsResponse"] as? [String:Any],
let aarti = response["aarti"] as? [[String:Any]] {
for item in aarti {
let content = item["content"] as! String
let identifier = item["identifier"] as! String
let title = item["title"] as! Int
let type = item["type"] as! String
print(content, identifier, title, type)
}
}
}
Basically do not use NSDictionary / NSArray in Swift.
If you want to put all content values in an array use flatMap. The line can replace the whole repeat loop.
let contentArray = aarti.flatMap { $0["content"] as? String }
PS: If you are going to create multiple arrays from the values don't do that: Use a custom struct or class
if someone want to get dictionary of array and use it in tableview
declaration:
var list:[Any] = []
and initialisation :
self.list = (self.ListDic?["data"] as! NSArray!) as! [Any]
and use:
let dictObj = self.list[indexPath.row] as! NSDictionary
print("object value: ",dictObj["text"] as! String)

Swift: Parsing Arrays out of JSONs

[{"name":"Air Elemental","toughness":"4","printings":["LEA","BTD","7ED","8ED","9ED","10E","DD2","M10","DPA","ME4","DD3_JVC"]}]
I have a JSON where there is an array in each listing called "printings" as seen below, how would I take this array out of each listing and convert it into a string like "LEA-BTD-7ED". Here is what I have so far but its crashing.
let err : NSErrorPointer?
let dataPath = NSBundle.mainBundle().pathForResource("cardata", ofType: "json")
let data : NSData = try! NSData(contentsOfFile: dataPath! as String, options: NSDataReadingOptions.DataReadingMapped)
do{
var contents = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as! [AnyObject]
for var i = 0;i<contents.count;++i{
let printing = contents[i]["printings"] as! String
}
}
Here's the code:
let path = dataPath!
if let JSONData = NSData(contentsOfFile: path)
{
do
{
if let dictionariesArray = try NSJSONSerialization.JSONObjectWithData(JSONData, options: NSJSONReadingOptions()) as?
[[String: AnyObject]]
{
for dictionary in dictionariesArray
{
if let printingsArray = dictionary["printings"] as? [String]
{
let printingsString = printingsArray.joinWithSeparator("-")
print(printingsString)
}
}
}
}
catch
{
print("Could not parse file at \(path)")
}
}
Executing it prints "LEA-BTD-7ED-8ED-9ED-10E-DD2-M10-DPA-ME4-DD3_JVC"
You can't cast an Array (contents[i]["printings"]) to a String. What you want is Array's joinWithSeparator() method, like this:
let printing = contents[i]["printing"] as! Array
let printingStr = printing.joinWithSeparator("-")
(Actually, I'm not sure whether you need the as! Array; try it without it.)

JSON To Array in Swift

I'm Using Swift2.0+, SwiftyJSON, Alamofire
I Got the Value let stringJSON:JSON = ["a1","a2","a3"] from Server
But If I Check stringJSON[0],Then it's null
When I debugPrint(stringJSON), Then it's ["a1","a2","a3"]
How Can I got the value stringJSON[0] //"a1" ?
Do I Have To Convert From JSON To Another?
The correct syntax is
let stringJSON:JSON = ["a1","a2","a3"]
if let firstValue = stringJSON.array?.first {
print(firstValue) // a1
}
Update
Since the value actually contains this string "[\"a1\/a1\",\"a2\/a2\",\"a3\"]" and you cannot fix this on the server side here it is a workaround.
if let words = stringJSON.string?.characters.dropFirst().dropLast().split(",").map(String.init) {
let word = String(words[0].characters.dropFirst().dropLast())
print(word) // a1
}
if let x = stringJSON[0].string{
print(x)
}
Since the server is not returning an Array, but a String, you need to convert that into an Array of Strings like this:
let string = stringJSON.string
let array = string.stringByReplacingOccurrencesOfString("[", withString: "")
.stringByReplacingOccurrencesOfString("]", withString: "")
.stringByReplacingOccurrencesOfString("\"", withString: "")
.componentsSeparatedByString(",")
stringJSONIf it is a string type, you can like this to solve:
extension String {
var parseJSONString: AnyObject? {
var any: AnyObject?
let data = self.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
do{
any = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers)
}catch let error as NSError{
print("error: \(error)")
}
return any
}
and use it like this:
let strArr = stringJSON.stringvalue.parseJSONString as! Array<String>

How to convert from a Swift String Set to an Array

I am trying to create an array of words from a string object retrieved from Parse. The object retrieved looks like this:
Then this line of code gives this.
let joinedWords = object["Words"] as! String
How do I convert joinedWords to an Array?
If you don't care about the order, you can use flatMap on the set:
var mySet = Set<String>()
for index in 1...5 {
mySet.insert("testwords\(index)")
}
let myArray = mySet.flatMap { $0 }
print(myArray) // "["testwords5", "testwords3", "testwords4", "testwords2", "testwords1"]"
If you want the list sorted alphabetically, you can make your array a var and use sortInPlace()
var myArray = mySet.flatMap { $0 }
myArray.sortInPlace()
print(myArray) // "["testwords1", "testwords2", "testwords3", "testwords4", "testwords5"]"
If object["Words"] is AnyObject, you will have to unwrap it.
if let joinedWordsSet = object["Words"] as? Set<String> {
var joinedWordsArray = joinedWordsSet.flatMap { $0 }
myArray.sortInPlace()
print(myArray)
}
Swift 3 note: sortInPlace() has been renamed sort().
Many thanks to #JAL for so much time on chat to solve this one. This is what we came up with. Its a bodge and no doubt there is a better way!
When uploading to Parse save the set as an array.
let wordsSet = (wordList?.words?.valueForKey("wordName"))! as! NSSet
let wordsArray = Array(wordsSet)
Then it saves to Parse - looking like a set, not an array or a dictionary.
let parseWordList = PFObject(className: "WordList")
parseWordList.setObject("\(wordsArray)", forKey: "Words")
parseWordList.saveInBackgroundWithBlock { (succeeded, error) -> Void in
if succeeded {
// Do something
} else {
print("Error: \(error) \(error?.userInfo)")
}
}
Then you can drop the [ ] off the string when its downloaded from Parse, and remove the , and add some "" and voila, there is an array that can be used e.g. to add to CoreData.
var joinedWords = object["Words"] as! String
joinedWords = String(joinedWords.characters.dropFirst())
joinedWords = String(joinedWords.characters.dropLast())
let joinedWordsArray = joinedWords.characters.split() {$0 == ","}.map{ String($0) } // Thanks #JAL!

Resources