How to sort JSON Data in Array in swift 4

sort array in ascending order swift 4
swift sort array of strings
swift sort array by two properties
how to sort array of dictionary in swift 4
sort array of dictionary by date swift 4
swift sort array of structs
json swift 5
swift json array

I have JSON array like this

 var json = NSArray()  // array with json objects

 //print json >>
   json = (
                Name = "Alen";
                Score = 500;
                Name = "John";
                Score = 0;
                Name = "Mark";
                Score = 2000;
                Name = "Steve";
                Score = 300;
                Name = "Ricky";
                Score = 900;

and i can access its objects as

(json[0] as! NSDictionary).object(forKey: "Name")
(json[0] as! NSDictionary).object(forKey: "Score")

I want to sort this JSON array according to scores.

I found the answers like

let sortedArray = json.sorted(by: { $0.0 < $1.0 })

which gives error

Value of type 'Any' has no member '0'

Then I tried this

 let sortedArray = (json as! NSDictionary).sorted {(aDic, bDic)  -> Bool in
                return aDic.key < bDic.key

It gave error

Binary operator '<' cannot be applied to two 'Any' operands

Can you please guide me to sort the array according to score in swift 4?

That's a very good example why you are strongly discouraged from using NSArray and NSDictionary in Swift.

Both collection types don't provide type information so everything is treated as Any. Most of the shared generic API of the Swift Standard library cannot be used with Any so you are not able to take advantage of the powerful generic functions unless you add a lot of ugly type casts.

If all values are String declare your array as

var json = [[String:String]]()

Then you can sort the array with

let sortedArray = json.sorted { $0["Score"]! < $1["Score"]! }

The most recommended solution is to decode the JSON directly into a custom struct

struct Player : Decodable {
    let name : String
    let score : String

    private enum CodingKeys : String, CodingKey { case name = "Name", score = "Score" }

Then you get rid of all type casting and you can sort by the property name

var players = [Player]()

let jsonString = """
[{"Name" : "Alen", "Score" : "500"},
{"Name" : "John", "Score" : "0"},
{"Name" : "Mark", "Score" : "2000"},
{"Name" : "Steve", "Score" : "300"},
{"Name" : "Ricky", "Score" : "900"}]

let data = Data(jsonString.utf8)
do {
    players = try JSONDecoder().decode([Player].self, from: data)
    let sortedPlayers = players.sorted{ $$1.score, options: .numeric) == .orderedAscending }
} catch { print(error) }


To load the JSON use an asynchronous way (URLSession)

Never load data from a remote URL with synchronous Data(contentsOf.

var players = [Player]()

let jsonUrl = URL(string: "url.json")! 
let task = URLSession.shared.dataTask(with : url) { [unowned self] (data, _, error) in 
    if let error = error { print(error); return }
    do {
        players = try JSONDecoder().decode([Player].self, from: data!).sorted{ $0.score < $1.score }
        DispatchQueue.main.async { // reload the table view if necessary
    } catch { print(error) }

nsarray - How to sort JSON Data in Array in swift 4, That's a very good example why you are strongly discouraged from using NSArray and NSDictionary in Swift. Both collection types don't provide type information  In Swift, you typically use a component called JSONSerializer to turn JSON into Swift objects and arrays. You can also use a fantastic 3rd-party library to make dealing with JSON easier, called SwiftyJSON. Before we find out how SwiftyJSON is different from JSONSerializer, let’s get into how you can use SwiftyJSON to work with JSON data.

After parsing your json, you can sort your score array like this

var scoreArray = ["500", "0", "2000", "300", "900"]
array.sort { $$1, options: .numeric) == .orderedAscending }

Swift - Sort an Array by Object's Value, Learn Swift coding for iOS with these free tutorials. Swift version: 5.1 All arrays have built-in sort() and sorted() methods that can be used to  All arrays have built-in sort() and sorted() methods that can be used to sort the array, but they are subtly different.. If the array is simple you can just call sort() directly, like this, to sort an array in place:

I did something like this before

First I created two arrays of dictionary

var jsonArray =  [(name:String, score:String)]()
var sortedscoreArray:[(name: String, score: String)] = []

and in getting json data you can create for loop

for I in 0..< jsonData.count{
  Let jsonInfo = jsonData[i]
  jsonArray.append((name: jsonInfo["Name"].string!, score: jsonInfo["Score"].string!))

and after you fill the json array pass it to sortedArray

sortedscoreArray =  jsonArray.sorted(by: { $0.score < $1.score })

How to sort an array using sort(), If you want to parse JSON by hand rather than using Codable , iOS has a and it can convert a JSON string into a collection of dictionaries, arrays, This then gets sent to JSONSerialization (by converting it into a Data if the JSON isn't valid, you need to use try/catch and have some sort of error handling. Now we can go ahead and decide the JSON data into an array of that Person struct. This is a throwing operation, so you need to use try. Here’s some example code: That will result in people storing the two items from the JSON, except now they are parsed into Swift types so we can refer to them in a type-safe way.

If array contains dictionary then you can use this code for sorting:

let sortedArray = json.sort { $0["Score"] as! Int < $1["Score"] as! Int }

and if you are using bean class then you can use dot(.) properties for sorting:

let sortedArray = json.sort { $0.Score < $1.Score }

How to parse JSON using JSONSerialization, SwiftyJSON makes it easy to deal with JSON data in Swift. But although explicit typing is good for saving us from mistakes, it becomes painful when dealing with Getting an array of string from a JSON Array let arrayNames = json["users"]. Since Swift is an object-oriented language use a custom struct as model. struct Fruit { let name : String let imageURL : NSURL let description : String } Declare an empty Swift array of Fruit as data source array. Basically use always Swift native collection types (rather than NSArray and NSDictionary) because they contain the type information.

SwiftyJSON/SwiftyJSON: The better way to deal with JSON , You can use <|* for now. Getting into the Nest. First, let's look at getting to the data within nested objects. A use case for this could be a Post  As it stands you're converting it to data, then attempting to convert the data to to an object as JSON (which fails, it's not JSON) and converting that to a string, basically you have a bunch of meaningless transformations.

Parsing Embedded JSON and Arrays in Swift, Array<Dictionary<String, Any>> products[0]["amount"] = 4 data?["products"] = products How can I send those original JSON arrays with Siesta? They're really  Sort array in ascending order. Problem. I have an Array and want to sort its contents (numeric or lexicographically) in ascending order. Recipe // Initialize the Array var a = [6,3,2,1,5,4] // Sort (ascending) its elements a = a.sort { $0 $1 } print(a)

Sorting JSON response alphabetically in Swift - json - html, How to parse JSON data taken from an API source into a dictionary in Apples We now have our JSON object as an array in swift so it's pretty easy to loop through There are many ways to do this sort of thing but for me this is what feels like  Open and Run Xcode and create a new project with File » New » Project ⌘⇧N. Select iOS » Application » Single View Application: Here, there will be two methods to load JSON Data one way will be through the .json file which will be stored in out project folder and other way is to parse JSON from URL .

  • Title of the question is Swift 4 and taggued with Swift 3, strange. Also, avoid using NSDictionary/NSArra in Swift, use Swift Dictionary/Array, event better: avoid NSStuff when available in Swift 3.
  • var json is not JSON so far, it is just an NSArray of NSDictionary. As @Larme mentioned, you should avoid using these guys if you could, go with native Swift collections (for instance [[String: Int]]).
  • And looks like you forgot to convert your dictionaries into objects (using structs or classes) which would greatly help managing this data. You should avoid using JSON and dictionaries directly, better use model objects.
  • sorry I am very new to swift, I have no idea how to do that..
  • @FaizyZaidy Look at vadian's answer.
  • Thanks alott @vadian This helped me alot, I am sorry I am new to swift, and I was getting my Json file like this let jsonUrl = URL(string: "url.json") do { let data = try Data(contentsOf: jsonUrl!) //let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary json = try (JSONSerialization.jsonObject(with: data, options:JSONSerialization.ReadingOptions.mutableContainers) as? NSArray)! would you suggest anything on this?
  • Thanks @Vadian I did exactly same but while printing players it says (CodingKeys in _D02FB714673388A51EFFF7A36D0361B0).score], debugDescription: "Expected to decode Int but found a string/data instead.", underlyingError: nil)
  • Then the value for Score is String, change the type in the declaration line: let score : String and you have to change the sort closure. I updated the answer.
  • I don't see in the question where OP is using SwiftyJSON... I think they're not using it...
  • @Moritz, i have updated my answer please check it again.
  • .intValue is a SwiftyJSON getter. I don't think OP uses SwiftyJSON.
  • The second error still occurs if the array is declared as NSArray. That's the main problem.