Tholle
Tholle

Reputation: 112867

Separating Google child labels from parent labels

I want to retrieve all labels a user has at Google and display them in a neat way, like Google themselves do:

enter image description here

When I fetch this hierarchy of labels with the Gmail API I get the following data:

GET https://www.googleapis.com/gmail/v1/users/me/labels?key={YOUR_API_KEY}

enter image description here

I use "/" as a delimiter in order to figure out the parent label of a certain child label. This worked great until I realized I could create labels with "/" in the name. Bummer.

Is there another way to do this, or should I stop my users from being able to create labels with "/" in them, and just live with the potential "bad" labels they might have created elsewhere? Thanks.

Upvotes: 0

Views: 242

Answers (1)

Steve Bazyl
Steve Bazyl

Reputation: 11692

It's possible to handle this case correctly, though it requires a little extra work than just splitting on the '/'.

Suppose you have the labels:

  • foo
    • bar
      • baz/qux

When you fetch all the labels, you'll get back 3 entries:

"foo" "foo/bar" "foo/bar/baz/qux"

Note that while "foo" and "foo/bar" exist, there is no "foo/bar/baz". That label doesn't exist because 'baz/qux' is the literal label name.

Rather than simply split, try prefix matching instead. The parent label is going to be the longest label (+ trailing /) that is a prefix of the one your checking. Anything remaining after the prefix is the label name itself.

Upvotes: 1

Related Questions