Display Just's JSON response as a collapsible tree

(Korakot Chaovavanich) #1

I learned to use Swift’s Just library a few days ago. Now I make it easier to explore a JSON response as a collapsible tree. Here’s a minimal colab example to share with you all.

The key part is this HTTPResult.display() extension.

extension HTTPResult 
{
  func display()
  {
    HTML("""
    <script src="https://cdn.jsdelivr.net/npm/renderjson/renderjson.js"></script>
    <script>
    renderjson.set_show_to_level(1)
    document.body.appendChild(renderjson(\(self.text!)))
    new ResizeObserver(google.colab.output.resizeIframeToContent).observe(document.body)
    </script>
    """).display()
  }
}

Usage is easy. The collapsible tree is displayed.

Just.get("http://httpbin.org/get", 
          params: ["page": 3]
        ).display()

Hope it is useful for new fellow learners of Swift.

4 Likes

(Korakot Chaovavanich) #2

Another snippet to share. This one let me write a text file easily. Just like %%writefile in a Python notebook.

%install '.package(url: "https://github.com/mxcl/Path.swift", .branch("master"))' Path

import Path

public extension String {
  func write(to path: String) throws -> String {
    let base = (path.first! == Character("/")) ? Path.root : Path.cwd
    return try write(to: base/path).string
  }
}

// Usage:
"""
Hello World (no newline)
""".write(to: "/hello.txt")
1 Like