1

I have an Array of dictionaries like this :

let arrayofDictionaries:[[String:Any]] = [
    ["nationalCode": "1570158037", "bookId": 327, "orderDate": "2017-07-24 14:11:52", "mobileNo": "09873456789", "isFavorite": false, "price": 45000, "bookName": "آموزش عربي انساني نکته ها"],
    ["nationalCode": "1570158037", "bookId": 366, "orderDate": "2017-07-24 14:11:58", "mobileNo": "09873456789", "isFavorite": false, "price": 19000, "bookName": "آبي عربي پيش1و2انساني"],
    ["nationalCode": "1570158037", "bookId": 327, "orderDate": "2017-07-24 14:11:52", "mobileNo": "09873456789", "isFavorite": false, "price": 45000, "bookName": "آموزش عربي انساني نکته ها"],
    ["nationalCode": "1570158037", "bookId": 366, "orderDate": "2017-07-24 14:11:58", "mobileNo": "09873456789", "isFavorite": false, "price": 19000, "bookName": "آبي عربي پيش1و2انساني"],
]

The Dictionary inside the array has fixed keys which values would change. I tried this code:

for item in arrayofDictionaries {
    for (kind, value) in item {
        print(kind)
        dic.updateValue(value!, forKey: kind)
    }    
}

but this would eliminate duplicate kies and just return the last values. the output of the above code would be:

dic = ["nationalCode": "1570158037", "bookId": 366, "orderDate": "2017-07-24 14:11:58", "mobileNo": "09873456789", "isFavorite": false, "price": 19000, "bookName": "آبي عربي پيش1و2انساني"]

what i want is a dictionary like this:

let flattenedArray : [String : Any] = [
    "nationalCode": "1570158037", "bookId": 327, "orderDate": "2017-07-24 14:11:52", "mobileNo": "09873456789", "isFavorite": false, "price": 45000, "bookName": "آموزش عربي انساني نکته ها",
    "nationalCode": "1570158037", "bookId": 366, "orderDate": "2017-07-24 14:11:58", "mobileNo": "09873456789", "isFavorite": false, "price": 19000, "bookName": "آبي عربي پيش1و2انساني",
    "nationalCode": "1570158037", "bookId": 327, "orderDate": "2017-07-24 14:11:52", "mobileNo": "09873456789", "isFavorite": false, "price": 45000, "bookName": "آموزش عربي انساني نکته ها",
    "nationalCode": "1570158037", "bookId": 366, "orderDate": "2017-07-24 14:11:58", "mobileNo": "09873456789", "isFavorite": false, "price": 19000, "bookName": "آبي عربي پيش1و2انساني",
]

any help would be appreciated

6
  • 8
    "what i want is a dictionary like this" - you can't have a dictionary like this, period. Dictionary's keys are unique and each refers to a single value. What are you trying to achieve with dictionary like this? Commented Jul 24, 2017 at 11:05
  • as @mag_zbc said, "What are you trying to achieve?", we can suggest you alternatives. Commented Jul 24, 2017 at 11:08
  • @mag_zbc I'm trying to do a post request. it should turn to a string. Commented Jul 24, 2017 at 11:12
  • What exactly do you mean by "it should turn to a string"? Give an example of your post request. Commented Jul 24, 2017 at 11:18
  • this is what my the web service needed POST /newsite/Common/WebService/WSPublicApp.asmx/InsertFactor HTTP/1.1 Host: city.kanoon.ir Content-Type: application/x-www-form-urlencoded Content-Length: length FactorInfo=string HTTP/1.1 200 OK Content-Type: text/xml; charset=utf-8 Content-Length: length <?xml version="1.0" encoding="utf-8"?> <string xmlns="tempuri.org/">string</string> . and i should post a string for requesting i suppose. and i want that arrayofDictionaries alter to a string so i can do the post reques. i'm new to this posting stuff sorry for Unclearity. Commented Jul 24, 2017 at 12:13

4 Answers 4

1
do {
        let data = try JSONSerialization.data(withJSONObject: JsoonFactor, options: .prettyPrinted)
        let jsonString = String(data: data, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue))
        let jr = (jsonString?.replacingOccurrences(of: "\n", with: "", options: .regularExpression))!
        let jrrr = jr.removingWhitespaces()
        let urlEncodedJson = jrrr.addingPercentEncoding( withAllowedCharacters: .urlQueryAllowed)
Sign up to request clarification or add additional context in comments.

Comments

1

From your comments we finally get what are you trying to do - you want to turn your arrayOfDictionaries to a String to post it with a request.

It may vary depending on how exactly you want it to look, but if you want to turn your arrayOfDictionaries to string, you can do something like this

var aString : String = ""
for aBook in arrayOfDictionaries {
    if let nationalCode = aBook["nationalCode"] {
        aString.append("nationalCode : " + nationalCode + ", ")
    }
    if let bookId = aBook["bookId"] {
        aString.append("bookId : " + bookId + ", ")
    }
    // and so on, and so forth
}

Why do it manually, instead of just iterating with (key, value) over the dictionary? Unfortunately, due to the fact that Dictionary is implemented as hash map, there is no guarantee that when iterating your keys will appear in the same order they were when you declared the dictionary (actually, it's almost guaranteed that the order will be different).

But again, it's the matter of format your string needs to have. If the order doesn't matter, just iterate with (key, value)

1 Comment

I need exactly the format in flattenedArray. the output of this code doesn't have brackets or double coats
0

Although I too didn't understand what exactly are you trying to achieve, but as you mentioned in the comment, to create a URL string from a dictionary , simply use:

func urlString() -> String
    {
        var string = ""

        for key in self.keys
        {
            if let value = self[key]
            {
                string += "&\(key)=\(value)"
            }
        }
        return string
    }

3 Comments

yes, i want to add in a URL string. is this working for [[String : Any]] ? or just [String : Any]
the method you were writing is not working for arrays of dictionaries it's just working for dictionaries
Yes it converts a dictionary into string. To convert an array of dictionaries, loop through the array and append the corresponding string.
0

Dictionaries are meant to be used with unique keys, it is probable that the process is not eliminating the duplicate keys but the creation itself, the dictionary class even has a function to create a dictionary defining the rules to decide which value to take as the correct from duplicated entries.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.