Convert Swift Dictionary to String
Just use the description
property of CustomStringConvertible
as
Note: Prior to Swift 3 (or perhaps before), CustomStringConvertible
was known as Printable
.
How to convert dictionary to json string without space and new line
You are decoding the serialized JSON into an object. When an object is printed into the console, you will see the indentation, and the use of equals symbols and parentheses.
Remove the .prettyPrinted
option and use the data to initialize a string with .utf8
encoding.
let jsonData = try! JSONSerialization.data(withJSONObject: requests, options: [])
let decoded = String(data: jsonData!, encoding: .utf8)!
Convert dictionary to query string in swift?
var populatedDictionary = ["key1": "value1", "key2": "value2"]
extension Dictionary {
var queryString: String {
var output: String = ""
for (key,value) in self {
output += "\(key)=\(value)&"
}
output = String(output.characters.dropLast())
return output
}
}
print(populatedDictionary.queryString)
// Output : key1=value1&key2=value2
Hope it helps. Happy Coding!!
Swift: convert [Dictionary String, [String : Double] .Element] to [String : [String : Double]]
I would use reduce(into:)
for this
let dictionary = decodedModel.reduce(into: [:]) {
$0[$1.name] = $1.model
}
Convert Any dictionary array to String in Swift
Here is one solution that actually gives the correct results:
let myarr = [
[
"Area" : "",
"Good" : "-",
"Level" : 2,
"Link" : "<null>",
"Photo" : "-",
"Repair" : "-",
"Section" : "Others"
],
[
"Area" : "",
"Good" : "N",
"Level" : 2,
"Link" : "http://someurl",
"Photo" : 1,
"Repair" : "Y",
"Section" : "Grounds"
]
]
var newarr = [[String:String]]()
for dict in myarr {
var newdict = [String:String]()
for (key, value) in dict {
newdict[key] = "\(value)"
}
newarr.append(newdict)
}
print(newarr)
Output:
[["Level": "2", "Area": "", "Good": "-", "Link": "<null>", "Repair": "-", "Photo": "-", "Section": "Others"], ["Level": "2", "Area": "", "Good": "N", "Link": "http://someurl", "Repair": "Y", "Photo": "1", "Section": "Grounds"]]
How to convert dictionary [String : Any] to [String : Float] in Swift
i think if you use cast like this:
let result: [String : [String: Double]]? = dict as? [String : [String: Double]]
but if you can't sure the dict's value type, but you need to find value which is eligible, you can use this function:
@inlinable public func compactMap<ElementOfResult>(_ transform: (Value) throws -> ElementOfResult?) rethrows -> [ElementOfResult]
like this:
let map = dict.values.compactMap { (value) -> [String : Double]? in
guard let valueMap = value as? [String: Any] else { return nil }
let filterResult = valueMap.filter { $0.value is Double }
return filterResult as? [String : Double]
}
How to convert a JSON string to a dictionary?
Warning: this is a convenience method to convert a JSON string to a dictionary if, for some reason, you have to work from a JSON string. But if you have the JSON data available, you should instead work with the data, without using a string at all.
Swift 3
func convertToDictionary(text: String) -> [String: Any]? {
if let data = text.data(using: .utf8) {
do {
return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
} catch {
print(error.localizedDescription)
}
}
return nil
}
let str = "{\"name\":\"James\"}"
let dict = convertToDictionary(text: str)
Swift 2
func convertStringToDictionary(text: String) -> [String:AnyObject]? {
if let data = text.dataUsingEncoding(NSUTF8StringEncoding) {
do {
return try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String:AnyObject]
} catch let error as NSError {
print(error)
}
}
return nil
}
let str = "{\"name\":\"James\"}"
let result = convertStringToDictionary(str)
Original Swift 1 answer:
func convertStringToDictionary(text: String) -> [String:String]? {
if let data = text.dataUsingEncoding(NSUTF8StringEncoding) {
var error: NSError?
let json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: &error) as? [String:String]
if error != nil {
println(error)
}
return json
}
return nil
}
let str = "{\"name\":\"James\"}"
let result = convertStringToDictionary(str) // ["name": "James"]
if let name = result?["name"] { // The `?` is here because our `convertStringToDictionary` function returns an Optional
println(name) // "James"
}
In your version, you didn't pass the proper parameters to NSJSONSerialization
and forgot to cast the result. Also, it's better to check for the possible error. Last note: this works only if your value is a String. If it could be another type, it would be better to declare the dictionary conversion like this:
let json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: &error) as? [String:AnyObject]
and of course you would also need to change the return type of the function:
func convertStringToDictionary(text: String) -> [String:AnyObject]? { ... }
How to convert Raw dictionary to JSON string?
For the purpose of focusing on getting the json string (without caring about how you got the dictionary), I would assume that your myDict
is the dictionary that you want to convert to json string:
let json = """
{
"event": {
"type": "message_create", "message_create": {
"target": {
"recipient_id": "RECIPIENT_USER_ID"
},
"message_data": {
"text": "Hello World!"
}
}
}
}
""".data(using: .utf8)
var myDict: [String: Any] = [: ]
do {
if let dict = try JSONSerialization.jsonObject(with: json!, options: []) as? [String: Any] {
myDict = dict
}
} catch {
print(error)
}
So now we want to convert myDict
as a json string:
do {
// converting `myDict` to Json Data, and then
// getting our json as string from the `jsonData`:
if let jsonData = try JSONSerialization.data(withJSONObject: myDict, options: []) as? Data,
let jsonString = String(data: jsonData, encoding: .utf8) {
print(jsonString)
}
} catch {
print(error)
}
jsonString
is now what are you looking for! you should see on the log:
{"event":{"type":"message_create","message_create":{"target":{"recipient_id":"RECIPIENT_USER_ID"},"message_data":{"text":"Hello
World!"}}}}
which is perfectly valid json.
Related Topics
How to Add "%" to Data in iOS-Chart
Subclass of Skspritenode in .Sks File
Uitableviewrowaction with Icon and Text
How to Select a Contact with Abpeoplepickernavigationcontroller in Swift
Swift, Pass Data Back from Popover to View Controller
Xcode10 - Dyld: Library Not Loaded for Pod Installed in Framework
Delegate Using Container View in Swift
How Safe Are Swift Collections When Used with Invalidated Iterators/Indices
Why Don't Structs Have Deinitializers in Swift Like Classes
Can You Use String/Character Literals Within Swift String Interpolation
Nsuserdefaults in Swift - Implementing Type Safety
How to Fix Error: This Class Is Not Key Value Coding-Compliant for the Key Tableview.'
Swift Uisearchcontroller Wired Up in Core Data Project, App Runs, But Search Not Updating
Swift: How Can String.Join() Work Custom Types
How to Automatically Reflect Coredata+Icloud Changes in Swiftui View
Swift + Nsviewcontroller Background Color (MAC App)
How to Check If Annotation Is Clustered (Mkmarkerannotationview and Cluster)