Advanced Xcode debugging: Creating an lldb alias for printing dictionaries as formatted JSON

The Xcode console gives you access to a powerful scriptable debugger: LLDB. One of the first LLDB commands I learned was po, which prints out the description of an Objective c or Swift object. I often find myself needing to display a Swift dictionary as a valid JSON string. Before I knew about LLDB I would write a couple of lines of code for encoding a dictionary to JSON, add a print statement, set a break point, recompile, copy the string from the console and then go on to remove escape characters to obtain valid JSON. Not OK. Let’s iterate through the process of streamlining this process.

Ditch print() statements

Since we have breakpoints and the ability to print application state to the console with po, there is really no need for littering the code with print() statements. Many times I have accidentally checked in a stray print() statements.

Ditch the recompile

LLDB is not just for printing out variables. You can write code to format the output.
Let’s say you have a Swift dictionary jsonDict that you would like to print out as a JSON string. Lets set the breakpoint and use po to do that:

po NSString(string: String(data: try! JSONSerialization.data(withJSONObject: jsonDict, options: .prettyPrinted), encoding: .utf8)!)

Alias!

If you follow an LLDB tutorial like this one you might thing the following should work:

command alias poj po NSString(string: String(data: try! JSONSerialization.data(withJSONObject: json, options: .prettyPrinted), encoding: .utf8)!)
command alias poj expression -O -l swift - - NSString(string: String(data: try! JSONSerialization.data(withJSONObject: jsonDict, options: .prettyPrinted), encoding: .utf8)!)
command alias poj expression -O -l swift - - NSString(string: String(data: try! JSONSerialization.data(withJSONObject: %1, options: .prettyPrinted), encoding: .utf8)!)

poj jsonDict
error: <EXPR>:3:75: error: ‘%’ is not a prefix unary operator
command regex poj ‘s/(.+)/expr NSString(string: String(data: try! JSONSerialization.data(withJSONObject: %1, options: .prettyPrinted), encoding: .utf8)!)/’
command regex poj ‘s/(.+)/expr print(NSString(string: String(data: try! JSONSerialization.data(withJSONObject: %1, options: .prettyPrinted), encoding: .utf8)!))/’
error: ‘poj’ is not a valid command.
error: Unrecognized command ‘poj’.

Load you aliases when starting Xcode

There is one last step left and you will be in dictionary JSON heaven. Create a file named .lldbinit in your user directory and add your alias to it. Files that start with a period are hidden files so either enable viewing of hidden files for Finder or use the command line to edit this file.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store