-1

I’d like to create a nested JSON string of installed font families and their associated fonts (which I could later send to a webview) using Swift 5.

I'm having trouble understanding Swift nested objects. Is there a specific type of object structure required by JSONSerialization?

var obj: [String: Any] = [:]
for family in UIFont.familyNames {
    var fonts: [String] = []
    for font in UIFont.fontNames(forFamilyName: family) {
        fonts.append(font)
    }
    obj[family] = fonts
}
do {
    let json = try JSONSerialization.data(withJSONObject: obj, options: .prettyPrinted)
    print(json) // Outputs ‘9415 bytes’ rather than JSON string (below)
} catch {}

I would like the JSON string to look something like:

{
  “Didot”:[“Didot”,”Didot-Italic”,”Didot-Bold”],
  “Impact”:[”Impact”],
  // etc
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Josiah
  • 1,117
  • 5
  • 22
  • 35
  • 1
    You should look at using `Codable` and `JSONEncoder`, but to answer your question, `json` is an instance of `Data`. Convert it to a String using `String(data: json, encoding:.utf8)` – Paulw11 Apr 03 '23 at 08:39

1 Answers1

2
let string = String(data: json, encoding: .utf8)!
print(string)
AnderCover
  • 2,488
  • 3
  • 23
  • 42