Skip to content

GDB pretty print support #1507

Open
Open
@y9luiz

Description

@y9luiz

It's pretty hard to debug programs with a complex JSON structure such as Json::Value, thinking on that.
I did create a very simple pretty print gdb script that would help you debug and see the content under yours JSON objects.

import gdb
import json
class JsonValuePrinter:
    def __init__(self, val):
        self.val = val

    def _invoke_to_styledString_(self):
        eval_string = f"(({self.val.type.name}*){self.val.address})->toStyledString().c_str()"
        output = json.loads(gdb.parse_and_eval(eval_string).string())
        return str(output)

    def to_string(self):
        return self._invoke_to_styledString_()

def build_pretty_printer(val):
    if str(val.type) == 'Json::Value':
        return JsonValuePrinter(val)

gdb.pretty_printers.append(build_pretty_printer)

The script is pretty simple and just converts the JSON to a styled string representation with the method Json::Value::toStyledString

Would be good to access each member individually, but it's considered more complex task So if someone already have a better script or even would like to improve mine, I would really appreciate it.

Anyways, to use this script just launch gdb in your program, for example:

#include <jsoncpp/json/json.h>
#include <jsoncpp/json/value.h>

#include <iostream>

int main()
{
  Json::Value val;

  val["xd"] = 10;

  Json::Value arr;

  arr.append(val);
  arr.append(val);

  val["complex json"] = arr;

  return 0;
}

compile it

g++ main.cpp -g -O0 -o run
gdb run
source prettyPrint.py

if you try to print val for example, you would see the following output:

image

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions