Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSDictionary find keyPath

I have a random dictionary, I want to iterate over all objects that are inside that dictionary. Is there a way to find keyPath of object that is inside the dictionary?

Let's say we have this dictionary .

{
  "glossary": {
    "title": "example glossary",
    "GlossDiv": {
      "title": "S",
      "GlossList": {
        "GlossEntry": {
          "ID": "SGML",
          "SortAs": "SGML",
          "GlossTerm": "Standard Generalized Markup Language",
          "Acronym": "SGML",
          "Abbrev": "ISO 8879:1986",
          "GlossDef": {
            "para": "A meta-markup language, used to create markup languages such as DocBook.",
            "GlossSeeAlso": [
              "GML",
              "XML"
            ]
          },
          "GlossSee": "markup"
        }
      }
    }
  }
}

Now I want to find keyPath of GlossEntry or any other object.

like image 503
Karen Karapetyan Avatar asked Jul 08 '26 22:07

Karen Karapetyan


1 Answers

Consider:

  1. You can obtain all the keys in a dictionary and iterate over them. E.g. for (NSString *key in dictionary) {...}

  2. Given a key you can obtain the matching value and test whether it is itself a dictionary.

  3. Recursion is your friend. You could write a function which takes a current key path prefix, a dictionary, and a mutable array to add found key paths to. The implementation of this would involve (1), (2) and a recursive call.

Now write yourself some code. If you get stuck ask a new question, include your code, and explain where you are stuck.

HTH

like image 165
CRD Avatar answered Jul 11 '26 11:07

CRD



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!