JSON To Array in Swift - arrays

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>

Related

Convert a string encoded array into an object

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 [[[]]]
}

How we can find an element from [AnyObject] type array in swift

I have [AnyObject] array
var updatedPos = [AnyObject]()
I am setting data in that according to my requirement like!
let para:NSMutableDictionary = NSMutableDictionary()
para.setValue(posId, forKey: "id")
para.setValue(posName, forKey: "job")
let jsonData = try! NSJSONSerialization.dataWithJSONObject(para, options: NSJSONWritingOptions())
let jsonString = NSString(data: jsonData, encoding: NSUTF8StringEncoding) as! String
self.updatedPos.append(jsonString)
Now in my code i have some requirement to remove the object from this array where id getting matched according to requirement Here is the code which i am trying to implement
for var i = 0; i < updatedPos.count; i++
{
let posItem = updatedPos[i]
print("Id=\(posItem)")
let pId = posItem["id"] as? String
print("secRId=\(pId)")
if removeId! == pId!
{
updatedPos.removeAtIndex(i)
}
}
Here print("Id=\(posItem)") give me output asId={"id":"51","job":"Programmer"} but here i am not able to access id from this object. here print("secRId=\(pId)") give me nil
First of all use native Swift collection types.
Second of all use types as specific as possible.
For example your [AnyObject] array can be also declared as an array of dictionaries [[String:AnyObject]]
var updatedPos = [[String:AnyObject]]()
Now create the dictionaries and add them to the array (in your example the dictionary is actually [String:String] but I keep the AnyObject values).
let para1 : [String:AnyObject] = ["id" : "51", "job" : "Programmer"]
let para2 : [String:AnyObject] = ["id" : "12", "job" : "Designer"]
updatedPos.append(para1)
updatedPos.append(para2)
If you want to remove an item by id use the filter function
let removeId = "12"
updatedPos = updatedPos.filter { $0["id"] as? String != removeId }
or alternatively
if let indexToDelete = updatedPos.indexOf{ $0["id"] as? String == removeId} {
updatedPos.removeAtIndex(indexToDelete)
}
The JSON serialization is not needed for the code you provided.
PS: Never write valueForKey: and setValue:forKey: unless you know exactly what it's doing.
After some little bit stuffs I have found the very easy and best solution for my question. And I want to do special thanks to #vadian. Because he teach me new thing here. Hey Thank you very much #vadian
Finally the answer is I had covert posItem in json Format for finding the id from Id={"id":"51","job":"Programmer"} this string
And the way is
let data = posItem.dataUsingEncoding(NSASCIIStringEncoding, allowLossyConversion: false)
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)
if let dict = json as? [String: AnyObject] {
let id = dict["id"]
if removeId! == id! as! String
{
updatedLoc.removeAtIndex(i)
}
}
}
catch {
print(error)
}

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.)

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!

how to change my String Value into Array by removing "()"

Let say I have values like this
Apple(100)
Orange(300)
Pineapple(10)
Grape(50)
Banana(1000)
What I want to do is to create an array which was like that to each string
["Apple","100"]
["Orange","300"]
What i tried was like that,but it doesn't meet my answer well enough
var myNewFruits = "Apple(200)"
var newStr = myNewFruits.componentsSeparatedByString("(")
The Output was
["Apple","200)"]
What i really want was
["Apple","200"]
Is there any help with Swift?Thank you.Because I am creating search with that,so,i really need it.
You can use a custom NSCharacterSet and get the first two elements from the returned array:
let myNewFruits = "Apple(200)"
let newStr = myNewFruits.componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString: "()"))[0...1] // ["Apple", "200"]
You can do it this way:
func stringToArr(str: String) -> [String] {
var newArr = [String]()
var fullNameArr = split(str) {$0 == "("}
newArr.append(fullNameArr[0])
var last: String? = fullNameArr.count > 1 ? fullNameArr[1] : nil
newArr.append(last!.stringByReplacingOccurrencesOfString(")", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil))
return newArr
}
var string = "Apple(100)" //"Apple(100)"
let newArr = stringToArr(string) //["Apple", "100"]

Resources