How to generate unique name for each JSON value
<p>I have following JSON, returned from a REST service, where I want to generate a unique names for each value by combining parent keys. For example. <code>name+phone+address+city+name</code> , <code>name+phone+address+city+population+skilled+male</code> and so on. </p>

<pre><code>{
  "name": "name",
  "phone": "343444444",
  "address": {
    "lat": 23.444,
    "lng": 34.3322,
    "city":{
      "name": "city name",
      "population": {
        "skilled": {
          "male": 2,
          "female": 4
        },
        "uneducated": {
          "male": 20,
          "femail": 4
        }
      }
    }
  },
  "email": "email",
  "education": "phd"
}
</code></pre>

<p>I want to combine all key names starting from the parent of the JSON tree.</p>

<p>Here is what I am doing</p>

<pre><code>class TestJson
     def walk_through(self, json_object):
        for k, v in json_object.items():
            self.x_path = self.x_path + k
            if type(v) is dict:
                self.walk_through(v)
            else:
                print(self.x_path)
                self.x_path = ""
</code></pre>

<p>This code is printing keys but only starting from the current parent node. I want to combine all keys up to root of the json. </p>

<p>If you ignore the <code>name</code> and <code>phone</code> keys, since they are not ancestors of <code>city name</code> or <code>skilled male</code> and the order of keys is not guaranteed, you can recursively build a flattened dict. </p>

<pre><code>def walk_through(json_object):
    d = {}
    for k, v in json_object.items():
        if isinstance(v, dict):
            v = walk_through(v)
            for vk, vv in v.items():
                d["%s+%s" % (k, vk)] = vv
        else:
            d[k] = v
    return d

print(json.dumps(walk_through(json_object), indent=2))
</code></pre>

<p>This prints:</p>

<pre><code>{
  "address+city+population+skilled+male": 2, 
  "name": "name", 
  "address+lng": 34.3322, 
  "address+city+name": "city name", 
  "address+lat": 23.444, 
  "address+city+population+uneducated+male": 20, 
  "phone": "343444444", 
  "address+city+population+uneducated+femail": 4, 
  "education": "phd", 
  "email": "email", 
  "address+city+population+skilled+female": 4
}
</code></pre>

<p><strong>Note:</strong> this ignores lists an will not find dicts inside them.</p>

python json python-3.x