swift 3 parse json array as key value - ios

i have a json, which i parse as a dictionary. Now most is simply a key value pair like "title":{"this is the title"}. The one thing bugging me is a key value pair that has an array for value.
"hashTags":[{"name":"pizza"},{"name":"salami"},{"name":"diet"}]
i do not want to use SwiftyJSON, since this is the only part i am unable to solve. What i need is to convert this value into an Array, which i can iterate. I had some approaches, they failed because they added new lines or stopped displaying äöü symbols.
Thank you in advance!

hashTags is an array of dictionaries with String keys and values, cast it to [[String:String]]
Iterate thru the array with a for loop and print all values for key name
if let hashTags = json["hashTags"] as? [[String:String]] {
for tag in hashTags {
print(tag["name"])
}
}
It's assumed that json is the parent object which contains the key hashTags.

All you need is using codable.
You can use Codable to parse Json to your desired model easily. you can check following document for more detail:
https://developer.apple.com/documentation/foundation/archives_and_serialization/using_json_with_custom_types
https://developer.apple.com/documentation/swift/codable

Related

How to sort array of dictionary by key?

I am trying to sort array of dictionary but not able to do it.
JSON Array : [{"2": "5"}, {"0": "1"}, {"1": "3"}, {"3": "6"}]
Expected Array : [{"0": "1"},{"1": "3"},{"2": "5"},{"3": "6"}]
I am trying this but not able to get expected result.
print(otpInputView.enteredValues.flatMap({ (dic) in
return dic.keys.sorted()
})
I am looking forward higher order functions output. (Manually I can achieve this)
Your code is sorting the dictionaries keys, but what you should do is sort the array, by the single dictionary key present. As you can see, the dictionaries in the output array are rearranged, which is why you should sort the array, not the dictionaries.
otpInputView.enteredValues.sorted {
...
}
Now we have the dictionaries $0 and $1, and we want to compare their single key (assuming all dictionaries have exactly one key). We can do that by:
otpInputView.enteredValues.sorted {
$0.keys.first! < $1.keys.first!
}
This sorts the keys by lexicographical order. The keys appear to all be numbers. If this is the case, and if you want them to be in numerical number, parse them to Ints first:
otpInputView.enteredValues.sorted {
Int($0.keys.first!)! < Int($1.keys.first!)!
}
I'm using a lot of ! here as I'm making many assumptions about the keys of the dictionary. Unwrap those optionals safely and fall back on default values if you can't make those assumptions.

How to get data from a property with a JSON document embedded using Cypher

I have the following case:
I have some information stored in Neo4j. One property store a JSON document, and I would like to get the information inside this JSON document.
I have retrieved the data, even the JSON field using MATCH:
MATCH (n:Node) RETURN n.id, n.nodeInfo as JSONInfo
JSONInfo (which is a property of Node), has the JSON Information:
{
"TIMESTAMP":"2018-03-11T04:58:24Z",
"field1":"358716053191804",
"field2":"732111149743974",
"version_field", "3.9.1"
"field3":"0",
"field4":"0"
}
But, I just want to get field1, that has inside JSON property.
What is the best way to retrieve this field in the MATCH command?
Thanks in advance
First of all your example isn't valid JSON. Your version_field key and value should be separated by a colon, not a comma, and you need a comma after "3.9.1".
{ "TIMESTAMP":"2018-03-11T04:58:24Z", "field1":"358716053191804", "field2":"732111149743974", "version_field":"3.9.1", "field3":"0", "field4":"0" }
Once that's fixed, and the field is valid JSON, you can use JSON conversion functions from APOC Procedures to do the conversion from a JSON object to a map, then just use dot notation to access map properties:
MATCH (n:Node)
RETURN apoc.convert.fromJsonMap(n.nodeInfo).field1 as field1
Keep in mind that map properties in JSON map strings cannot be indexed, so the data within your JSON string property should be used for storage and retrieval, not for lookup.

Convert NSNumber to String to support .sort() method in Swift?

I am receiving some Dictionary data which contains keys 'description'and 'volume'. I need to sort the dictionary based upon that and assign it to an array which will in turn load my UITableView.
I am able to sort based on description with nameArr.append((unSortedHoldingsArr[i]["description"] as? String).initializeStringIfNil)
where nameArr is declared as var nameArr : [String] = [] but when i am trying to sort it based upon volume the nameArr is getting filled with blank data. I am assuming the 'volume' contains data in NSNumber format. I want to make sure any kind of data coming from dictionary should get converted to String format to support the data in array.

Creating a case-insensitive dictionary in swift

In the application I'm writing I have a dictionary with a key named "Name". A user will then input text into a UITextField object then I insert the textField.text into a function that searches the JSON dictionary for that value for the key "Name". The problem I have is if the user types in "tyler" and the value in the JSON file is "Tyler" that value isn't retrieved. Also the JSON file is of type:
[String: AnyObject]
What is the best way to ensure case insensitivity with this in mind?
Thanks
Perhaps you could change your dictionary to
[String : (String,AnyObject)]
This way you could store the lowercase (or all uppercase) "key" in as the key, and then your tuple could have the actual spelling (if this matters) and the AnyObject as the 2nd item of the tuple.

Swift - Stored values order is completely changed in Dictionary

I tried to display datas which is in Dictionary format. Below, three attempts are there. First attempt, output order is completely changed. Second attempt, output order is same as input. But, in third attempt, I declared variable as NSDictionary. Exact output I received. Why this changes in Dictionary? Kindly guide me. I searched for Swift's Dictionary tag. But I couldn't found out.
//First Attempt
var dict : Dictionary = ["name1" : "Loy", "name2" : "Roy"]
println(dict)
//output:
[name2: Roy, name1: Loy]
//Second Attempt
var dict : Dictionary = ["name2" : "Loy", "name1" : "Roy"]
println(dict)
//output:
[name2: Loy, name1: Roy]
-----------------------------------------------------------
//Third Attempt With NSDictionary
var dict : NSDictionary = ["name1" : "Loy", "name2" : "Roy"]
println(dict)
//output:
{
name1 = Loy;
name2 = Roy;
}
ANOTHER QUERY: I have used play ground to verify. My screen shot is below:
Here, In NSDictionary, I gave name5 as first, but in right side name2 is displaying, then, in println, it is displaying in ascending order. Why this is happening??
Here, In Dictionary, I gave name5 as first, but in right side name2 is displaying, then, in println, it is displaying, how it is taken on the Dictionary line. Why this is happening??
This is because of the definition of Dictionaries:
Dictionary
A dictionary stores associations between keys of the same type and values of the same type in an collection with no defined ordering.
There is no order, they might come out differently than they were put in. This is comparable to NSSet.
Edit:
NSDictionary
Dictionaries Collect Key-Value Pairs. Rather than simply maintaining an ordered or unordered collection of objects, an NSDictionary stores objects against given keys, which can then be used for retrieval.
There is also no order, however there is sorting on print for debugging purposes.
You can't sort a dictionary but you can sort its keys and loop through them as follow:
let myDictionary = ["name1" : "Loy", "name2" : "Roy", "name3" : "Tim", "name4" : "Steve"] // ["name1": "Loy", "name2": "Roy", "name3": "Tim", "name4": "Steve"]
let sorted = myDictionary.sorted {$0.key < $1.key} // or {$0.value < $1.value} to sort using the dictionary values
print(sorted) // "[(key: "name1", value: "Loy"), (key: "name2", value: "Roy"), (key: "name3", value: "Tim"), (key: "name4", value: "Steve")]\n"
for element in sorted {
print("Key = \(element.key) Value = \(element.value)" )
}
A little late for the party but if you want to maintain the order then use KeyValuePairs, the trade-off here is that if you use KeyValuePairs you lose the capability of maintaining unique elements in your list
var user: KeyValuePairs<String, String> {
return ["FirstName": "NSDumb",
"Address": "some address value here",
"Age":"30"]
}
prints
["FirstName": "NSDumb", "Address": "some address value", "Age": "30"]
Dictionaries, by nature, are not designed to be ordered, meaning that they're not supposed to be (although they can be!).
From the Dictionaries (Swift Standard Library documentation):
A dictionary is a type of hash table, providing fast access to the entries it contains. Each entry in the table is identified using its key, which is a hashable type such as a string or number. You use that key to retrieve the corresponding value, which can be any object. In other languages, similar data types are known as hashes or associated arrays.
This requires some basic knowledge of Data Structures, which I'll outline & oversimplify briefly.
Storing associated data without a dictionary
Consider for a minute if there was no Dictionary and you had to use an array of tuples instead, to store some information about different fruits and their colors, as another answer suggested:
let array = [
("Apple", "Red"),
("Banana", "Yellow"),
// ...
]
If you wanted to find the color of a fruit you'd have to loop through each element and check its value for the fruit, then return the color portion.
Dictionaries optimize their storage using hash functions to store their data using a unique hash that represents the key that is being stored. For swift this means turning our key—in this case a String—into an Int. Swift uses Int-based hashes, which we know because we all read the Hashable protocol documentation and we see that Hashable defines a hashValue property that returns an Int.
Storing associated data with a dictionary
The benefits of using a dictionary are that you get fast read access and fast write access to data; it makes "looking up" associated data easy and quick. Typically O(1) time complexity, although the apple docs don't specify, maybe because it depends on the key type's hash function implementation.
let dictionary = [
"Apple": "Red",
"Banana": "Yellow"
// ...
]
The trade off is that the order is typically not guaranteed to be preserved. Not guaranteed means that you might get lucky and it might be the same order, but it's not intended to be, so don't rely on it.
As an arbitrary example, maybe the string "Banana" gets hashed into the number 0, and "Apple" becomes 4. Since we now have an Int we could, under the hood, represent our dictionary as an array of size 5:
// what things *might* look like under, the hood, not our actual code
// comments represent the array index numbers
let privateArrayImplementationOfDictionary = [
"Yellow", // 0
nil, // 1
nil, // 2
nil, // 3
"Red", // 4
] // count = 5
You'll notice, we've converted our keys into array indices, and there are a bunch of blank spaces where we have nothing. Since we are using an array, we can insert data lightning fast, and retrieve it just as quickly.
Those nil spaces are reserved for more values that may come later, but this is also why when we try to get values out of a dictionary, they might be nil. So when we decide to add more values, something like:
dictionary["Lime"] = "Green" // pretend hashValue: 2
dictionary["Dragonfruit"] = "Pink" // pretend hashValue: 1
Our dictionary, under the hood, may look like this:
// what things *might* look like under, the hood, not our actual code
// comments represent the array index numbers
let privateArrayImplementationOfDictionary = [
"Yellow", // 0 ("Banana")
"Pink", // 1 ("Dragonfruit")
"Green", // 2 ("Lime")
nil, // 3 (unused space)
"Red", // 4 ("Apple")
] // count = 5
As you can see, the values are not stored at all in the order we entered them. In fact, the keys aren't even really there. This is because the hash function has change our keys into something else, a set of Int values that give us valid array indices for our actual storage mechanism, an array, which is hidden from the world.
I'm sure that was more information than you wanted and probably riddled with many inaccuracies, but it gives you the gist of how a dictionary works in practice and hopefully sounds better than, "that's just how it works."
When searching for the actual performance of Swift dictionaries, Is Swift dictionary ... indexed for performance? ... StackOverflow had some extra possible relevant details to offer.
If you're still interested to know more details about this, you can try implementing your own dictionary as an academic exercise. I'd also suggest picking up a book on Data Structures and Algorithms, there are many to choose from, unfortunately I don't have any suggestions for you.
The deeper you get into this topic the more you'll understand why you'll want to use one particular data structure over another.
Hope that helps!
✅ It is possible!
Although the Dictionary is not ordered, you can make it preserve the initial order by using the official OrderedDictionary from the original Swift Repo
The ordered collections currently contain:
Ordered Dictionary (That you are looking for)
Ordered Set
They said it is going to be merged in the Swift's source code soon (reference WWDC21)
Neither NSDictionary nor Swift::Dictionary orders its storage. The difference is that some NSDictionary objects sort their output when printing and Swift::Dictionary does not.
From the documentation of -[NSDictionary description]:
If each key in the dictionary is an NSString object, the entries are
listed in ascending order by key, otherwise the order in which the
entries are listed is undefined. This property is intended to produce
readable output for debugging purposes, not for serializing data.
From The Swift Programming Language:
A dictionary stores associations between keys of the same type and values of the same type in an collection with no defined ordering.
Basically, order of items as seen in output is arbitrary, dependant on internal implementation of data structure, and should not be relied on.
This is indeed an issue with dictionaries. However, there's a library available to make sure the order stays the way you initialised it.
OrderedDictionary is a lightweight implementation of an ordered dictionary data structure in Swift.
The OrderedDictionary structure is an immutable generic collection which combines the features of Dictionary and Array from the Swift standard library. Like Dictionary it stores key-value pairs and maps each key to a value. Like Array it stores those pairs sorted and accessible by a zero-based integer index.
Check it out here:
https://github.com/lukaskubanek/OrderedDictionary

Resources