Skip to content

Instantly share code, notes, and snippets.

@johnno1962
Last active April 29, 2017 21:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnno1962/0b6b0853975c12f1176564ebfe7ac360 to your computer and use it in GitHub Desktop.
Save johnno1962/0b6b0853975c12f1176564ebfe7ac360 to your computer and use it in GitHub Desktop.
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