This question does not solve my issue.
I aim at printing out a JSON valid formatted dictionary, but I wanted to add items to this dictionary over a for loop. The resulting JSON file should look like:
"{
"items": [{
"name":"An Item"
},{
"name":"Item 2"
}]
}"
The below code works partially.
func buildItem(name: String) -> [String:Any] {
let action : [String: Any] = [
"name": name
]
return action
}
var items : [String: Any] = [:]
for filename in filelist {
items[filename] = buildItem(name: filename)
}
print (items)
If the directory has a file called test.md, the above returns:
["test.md": ["name": "test.md"]]
However I want it to return:
["items": ["name": "test.md"], ["name": "file2.md"]]
So I can convert into valid JSON.
- How can I add the returned entry from buildItem into
items
?
The entire code can be found in this pastebin.
So the problem is that you are adding the result of buildItem
to your dictionary as values for different keys instead of appending them to an array as the value for the items
key.
Basically, what you want is items["items"] = [array of buildItem results]
.
So, you need to replace your for loop with
var items : [String: Any] = [:]
items["items"] = filelist.map { buildItem(name: $0) }
and then serialize the dictionary into data and convert it to string you can simply use this simple extension for dictionaries with string keys
extension Dictionary where Key == String {
func toPrettyJSON() throws -> String {
let jsonData = try JSONSerialization.data(withJSONObject: self,
options: [.prettyPrinted])
guard let jsonStr = String(data: jsonData, encoding: .ascii)
else { throw NSError.init() }
return jsonStr
}
}
and then print your JSON
if let jsonStr = try? items.toPrettyJSON() {
print(jsonStr)
}
here is the entire code
You have to change items type to array because you can't take same keys for multiple values. In dictionary, every keys are distinct.
So just add more file names into filelist by append function of array.