Last active
April 29, 2017 21:07
-
-
Save johnno1962/0b6b0853975c12f1176564ebfe7ac360 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let bookTuples = [(1, "john", "book", "novel", 9.99, ["chapt1", "chapt2"]), | |
(2, "john", "book", "novel", 9.99, ["chapt1", "chapt2"])] | |
// leaves blank line when there are no values in the list | |
let json1 = """ | |
{ | |
"catalog": [ | |
\(bookTuples.map { | |
(id, author, title, genre, price, chapters) in """ | |
{ | |
"id": "id\(id)", | |
"author": "\(author)", | |
"title": "\(title)", | |
"genre": "\(genre)", | |
"price": \(price), | |
"chapters": [ | |
\(chapters.map { | |
(heading) in """ | |
"\(heading)" | |
"""}.joined(separator:",\n")) | |
] | |
} | |
"""}.joined(separator:",\n")) | |
] | |
} | |
""" | |
// no blank line but extra comma at the end | |
let json2 = """ | |
{ | |
"catalog": [ | |
\(bookTuples.map { | |
(id, author, title, genre, price, chapters) in """ | |
{ | |
"id": "id\(id)", | |
"author": "\(author)", | |
"title": "\(title)", | |
"genre": "\(genre)", | |
"price": \(price), | |
"chapters": [ | |
\(chapters.map { | |
(heading) in """ | |
"\(heading)", | |
"""}.joined(separator:"") | |
) ] | |
}, | |
"""}.joined(separator:"") | |
) ] | |
} | |
""" | |
print(""" | |
<?xml version="1.0"?> | |
<catalog> | |
\(bookTuples.map { | |
(id, author, title, genre, price, chapters) in """ | |
<book id="bk\(id)" empty=""> | |
<author>\(author)</author> | |
<title>\(title)</title> | |
<genre>\(genre)</genre> | |
<price>\(price)</price> | |
<chapters> | |
\(chapters.map { | |
(heading) in """ | |
<heading>\(heading)</heading> | |
"""}.joined(separator:"") | |
) </chapters> | |
</book> | |
"""}.joined(separator:"") | |
)</catalog> | |
""") | |
// elided newlines with no trailing newline stripping | |
print(""" | |
<?xml version="1.0"?> | |
<catalog> | |
\(bookTuples.map { | |
(id, author, title, genre, price, chapters) in """ | |
<book id="bk\(id)" empty=""> | |
<author>\(author)</author> | |
<title>\(title)</title> | |
<genre>\(genre)</genre> | |
<price>\(price)</price> | |
<chapters> | |
\(chapters.map { | |
(heading) in """ | |
<heading>\(heading)</heading> | |
"""}.joined(separator:""))\ | |
</chapters> | |
</book> | |
"""}.joined(separator:""))\ | |
</catalog> | |
""") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment